C Programming - Control Instructions - Discussion
Discussion Forum : Control Instructions - Point Out Errors (Q.No. 1)
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;
}
Answer: Option
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
Discussion:
5 comments Page 1 of 1.
Shyam said:
1 decade ago
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.
Manjunath K said:
1 decade ago
Why it will print the 1 initially can anyone please explain ?
Raju Royal said:
1 decade ago
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 :)
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 :)
Rupinderjit Singh said:
1 decade ago
Condition only breaks if i>10?
Hemanth said:
1 decade ago
The 1 is printed and if condition it breaks. How it prints 1 to 10? plzzz anyone.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers