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 4 of 5.

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.

Atul tailwal said:   1 decade ago
If x=1, y=1
y=x++<=5 it means first times x=1 and y=1 (not y=2) because x++ is preincreament , means first increament then assign. so loop will repeat 6 times.

Rashmi said:   1 decade ago
Thank you atul.

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.

Kailash singh said:   1 decade ago
Thank you for explanation.

Ravindar said:   1 decade ago
Thank for explanation to ravindara, kiran, and laxam.

Panchanan rauta said:   1 decade ago
Here the execution as like below

step-1 y=x++<=5; here x is post increment '1' is compare<=5 true y=1
then x increment print x=2 y=1

step2 2<=5 x become 3 and y=1 print x=3 y=1

step3 3<=5 x become 4 and y=1 print x=4 y=1

step4 4<=5 x become 5 and y=1 print x=5 y=1

step5 5<=5 x become 6 and y=1 print x=6 y=1

step6 6<=5 x become 7 and y=0 print x=7 y=0

step7 it check y become false loop will terminate

Hence the result is
2 1
3 1
4 1
5 1
6 1
7 0

Mohit singhal said:   1 decade ago
We can increase the value of x until the condition of y not become false.


Post your comments here:

Your comments will be displayed after verification.