C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Find Output of Program (Q.No. 13)
13.
What will be the output of the program?
#include<stdio.h>
int main()
{
    int x=1, y=1;
    for(; y; printf("%d %d\n", x, y))
    {
        y = x++ <= 5;
    }
    printf("\n");
    return 0;
}
2 1
3 1
4 1
5 1
6 1
7 0
2 1
3 1
4 1
5 1
6 1
2 1
3 1
4 1
5 1
2 2
3 3
4 4
5 5
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
46 comments Page 1 of 5.

Ravindar Nath Mishra said:   2 decades ago
Here the condition for the loop is y i.e until the y is true and in c true is assigned as 1 while false as 0 and x++ is post increment that is incremented after being used.

First Iteration x=1 y=(1<=5) which is true therefore y=1 and since x is post increment hence it is printed as 2,thus, x=2 and y=1 gets printed similarly for x=2,x=3,x=4.

On x=5 y=(5<=5) again y is true therefore y=1 and x=6 gets printed . BUT for x=6 y=(6<=5;which is false) so y=0 hence x=7 and y=0 get displayed. Since y=0 which is false thus loop gets terminated.

Kiran said:   1 decade ago
Here, x and y are inialized to 1,
In for loop, the condition statement is y = 1, it is true.
The next statements in for will executes.
y = x++ <= 5, here x++ will take the value 1 and (1 <= 5) is true x++ will becomes 2 1.e., x = 2 and y = 1 .
Then the incremented statement prints, x = 2 y = 1 it till upto x = 5 and y= 1

Here y = x++ <=5, evaluates to x = 6 (5 <= 5 it is true and x increment to 1) and
y = 1

Here 6 < = 5 is false, then y = 0, and x increments to 1 i.e., x = 7,
Then it prints x = 7 and y = 0.
Then Checks condition y = 0 which is fails, it comes out from the loop
The result is
2 1
3 1
4 1
5 1
6 1
7 0

Amar said:   1 decade ago
Thanks for the explanation!!

Nitin said:   1 decade ago
Thank you kiran for explain in this manner.

Bt I don't understood the last point when x=6 and y=0.

Viki said:   1 decade ago
When the condition fails, the why will be zero, but the x will be 7.

Bhaskar said:   1 decade ago
Thank you kiran.

Nandha said:   1 decade ago
If it's y = x++ <=5 false then boolean literal is 0, so y value is 0.

Raja said:   1 decade ago
thanks for explination.give brief explination

Ashwini said:   1 decade ago
THANX 4 YOUR EXPLANATION

Ramnayan said:   1 decade ago
Thanks for explanation mishra ji.


Post your comments here:

Your comments will be displayed after verification.