C Programming - Control Instructions - Discussion

1. 

Point out the error, if any in the for loop.

#include<stdio.h>
int main()
{
    int i=1;
    for(;;)
    {
        printf("%d\n", i++);
        if(i>10)
           break;
    }
    return 0;
}

[A]. There should be a condition in the for loop
[B]. The two semicolons should be dropped
[C]. The for loop should be replaced with while loop.
[D]. No error

Answer: Option D

Explanation:

Step 1: for(;;) this statement will genereate infinite loop.
Step 2: printf("%d\n", i++); this statement will print the value of variable i and increement i by 1(one).
Step 3: if(i>10) here, if the variable i value is greater than 10, then the for loop breaks.

Hence the output of the program is
1
2
3
4
5
6
7
8
9
10


Hemanth said: (Jul 23, 2011)  
The 1 is printed and if condition it breaks. How it prints 1 to 10? plzzz anyone.

Rupinderjit Singh said: (Oct 4, 2011)  
Condition only breaks if i>10?

Raju Royal said: (Feb 25, 2012)  
for(;;) - statement will genereate infinite loop.
to terminate this infinate loop we have to use break;

but break; statement gets executed only when if(i>10) is satisfied.

So the for(;;) loop iterates for the values 1,2,...9,10.
but when i increments to 11, if(i>10) is satisfied and break; terminates the for(;;) loop :)

Manjunath K said: (Aug 12, 2014)  
Why it will print the 1 initially can anyone please explain ?

Shyam said: (Oct 31, 2014)  
i++ means it performs post increment, means first it will assign initial value of i i.e., i = 1 and then it will increment i.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.