Problem Statement - Output writing – Three for loops
Write the output of the following code. Assume all header files are included.
int main()
{
int i;
for(i=10; i>6; i=i-2) cout<<i<<" ";
cout<<endl;
for(i=-5; i> -8; i--) cout<<i+1<<" ";
cout<<endl;
for(i=-3,sum=0; i<3; i--) cout<<sum++<<" ";
cout<<endl;
return 0;
}
Solution
Run Output
Solved Problem Understanding
Notes
int i,sum;
Variable i is declared here as it is used in all loops. variable sum is used in third loop. Both these variables can be declared in respective loops also.
for(i=10; i>6; i=i-2) cout<<i<<” “;
This one run 2 times value of i as 10 and i as 8 .
for(i=-5; i> -8; i–) cout<<i+1<<” “;
This loop runs 3 times for -5, -6 and -7 but prints one higher value as -4,-5 and -6
for(i=-3,sum=0; i<3; i++) cout<<sum++<<” “;
This loop runs 6 times for -3,-2,-1,0,1,2 and prints sum starting from 0 to 5 .
Common Errors
- Always watch for correct loop count and respective value changes by dry running the loop.
