Worksheet 4 (Looping Statements One)
Worksheet 4 (Looping Statements One)
1. Hand trace the following ‘while statements‘ and tell their outputs.
a.
while(0) f.
cout<<"Hellow world\n"; int count=2;
while(count<=8)
b. {
cout<<count<<" ";
while(1) count++;
cout<<"Hellow world\n"; }
c. if(count==9)
cout<<"\ncount = "<<count+1;
while(1); else
cout<<"Hello world \n"; cout<<"\ncount = "<<count+2;
d.
g.
int i=1;
while(i<=5) int maxSize=5;
{ float num, average,sum=0;
cout<<"Hellow world\n"; int i=1;
i++;
} cout<<"\nEnter 5 numbers\n\n";
// Say the user enters 10,20,30,40 & 50
while(i<=maxSize)
e. {
int k=5; cout<<"Number "<<i<<" = ";
while(k>=1) cin>>num;
{ sum=sum+num;
cout<<endl<<k<<" "; i++;
k--; }
} average=sum/maxSize;
cout<<"\nSum = "<<sum;
cout<<"\nAverage = "<<average;
Page | 1
2. Hand trace the following ‘do… while’ statements and tell their outputs.
a. }while(j>=0);
do
cout<<"Hellow world\n";
while(0);
f.
b.
do float num;
cout<<"Hellow world\n"; int flag;
while(1); cout<<"\nEnter any number\n\n";
// Say the user enters 10,20,30,40 & 50
c. do
{
int i=1;
cout<<"Number = ";
do
cin>>num;
{
if(num<0)
cout<<"Hellow world\n";
{
i++;
cout<<"You have just"
} while(i<=5);
<<"entered a -ve no.";
d. flag=0;
int count=3; }
do else if(num==0)
{ {
cout<<count<<" "; cout<<"You have just"
count++; <<"entered zero.";
}while(count<=9); flag=0;
}
e.
else
int j=6;
flag=1;
do
{
}while(flag==1);
cout<<j<<" ";
j--;
cout<<"\nYou are out of the Loop";
3. Hand trace the following ‘for statements‘ and tell their outputs.
a.
d.
int i;
for(i=0; i<=5; i++) int i=0;
cout<<i<<" "; for( ; i<=5 ; i++)
cout<<i<<" ";
b.
e.
for(int i=0; i<6; i++) int i=0;
cout<<i<<" "; for( ; i<=5 ; )
{
c. cout<<i<<" ";
i++;
for(int i=0; i<=5; i=i+1) }
cout<<i<<" ";
Page | 2
f.
Page | 3