C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Find Output of Program (Q.No. 1)
1.
What will be the output of the program?
#include<stdio.h>
int main()
{
    int i=0;
    for(; i<=5; i++);
        printf("%d", i);
    return 0;
}
0, 1, 2, 3, 4, 5
5
1, 2, 3, 4
6
Answer: Option
Explanation:

Step 1: int i = 0; here variable i is an integer type and initialized to '0'.
Step 2: for(; i<=5; i++); variable i=0 is already assigned in previous step. The semi-colon at the end of this for loop tells, "there is no more statement is inside the loop".

Loop 1: here i=0, the condition in for(; 0<=5; i++) loop satisfies and then i is incremented by '1'(one)
Loop 2: here i=1, the condition in for(; 1<=5; i++) loop satisfies and then i is incremented by '1'(one)
Loop 3: here i=2, the condition in for(; 2<=5; i++) loop satisfies and then i is incremented by '1'(one)
Loop 4: here i=3, the condition in for(; 3<=5; i++) loop satisfies and then i is increemented by '1'(one)
Loop 5: here i=4, the condition in for(; 4<=5; i++) loop satisfies and then i is incremented by '1'(one)
Loop 6: here i=5, the condition in for(; 5<=5; i++) loop satisfies and then i is incremented by '1'(one)
Loop 7: here i=6, the condition in for(; 6<=5; i++) loop fails and then i is not incremented.

Step 3: printf("%d", i); here the value of i is 6. Hence the output is '6'.

Discussion:
21 comments Page 2 of 3.

Dinesh said:   8 years ago
Great explanation @Sundar.

Aravind kumar said:   9 years ago
Thanks for your explanation @Sundar.

Sri said:   1 decade ago
The for loop in this program has a semi colon at the end of statement means their is no statements in loop to repeat after complition of loop the incremented value is assigned, here I takes 6 and it is displayed.

Ayush gupta said:   1 decade ago
Even if you don't initialize i with zero it will print 6. So does for loop initialize loop variable by 0?

Priyanka said:   1 decade ago
@Manish.

What you are thinking is wrong. Because after repeating for the 5th time I satisfies the condition because you have i<=5. So the condition is correct and I will be incremented further and its value become 6. Your assumption is true when the condition is i<5.

Manish said:   1 decade ago
This program has been output 5 because increment 5 times.

Shaswati said:   1 decade ago
Many many many thanks to indiabix for providing an online compiler...its really very much helpful ..thanks a lot

Puspita said:   1 decade ago
Thanks sundar.

Vaibhav said:   1 decade ago
Pay attention towards for loop , there is semicolon at the end of for loop .It means the loop will execute for given condition but control will remain at the same line till the loop get exhausted. Hence when control passes to next line the value of I become 6.

Vinoth M said:   1 decade ago
Thank you sundar very good explanation.


Post your comments here:

Your comments will be displayed after verification.