C Programming - Expressions - Discussion
Discussion Forum : Expressions - Find Output of Program (Q.No. 8)
8.
What will be the output of the program?
#include<stdio.h>
int main()
{
int x=4, y, z;
y = --x;
z = x--;
printf("%d, %d, %d\n", x, y, z);
return 0;
}
Answer: Option
Explanation:
Step 1: int x=4, y, z; here variable x, y, z are declared as an integer type and variable x is initialized to 4.
Step 2: y = --x; becomes y = 3; because (--x) is pre-decrement operator.
Step 3: z = x--; becomes z = 3;. In the next step variable x becomes 2, because (x--) is post-decrement operator.
Step 4: printf("%d, %d, %d\n", x, y, z); Hence it prints "2, 3, 3".
Discussion:
26 comments Page 2 of 3.
Gunu said:
9 years ago
I didn't get how x=2?
Raj said:
9 years ago
Y =--x in this case x is decremented first and then after the value of x is assigned to y. So x becomes 3 and y is also 3.
Z =x-- here first the value of x is assigned to z first and then it is decremented so z is 3 and x becomes 3 - 1 = 2.
Z =x-- here first the value of x is assigned to z first and then it is decremented so z is 3 and x becomes 3 - 1 = 2.
Ninad said:
9 years ago
Thanks @Raj.
Soumen das said:
9 years ago
How it is 2 3 3? Explain me.
Siri said:
8 years ago
y=--x means first x is decremented and then assign x value to y.
So, here x=4, x is decremented so x= 3 then assign x to y hence y=3.z=x-- means first x value is assigned to z and then x value is decremented hence z=3 and x=2.
So, here x=4, x is decremented so x= 3 then assign x to y hence y=3.z=x-- means first x value is assigned to z and then x value is decremented hence z=3 and x=2.
Abhi said:
7 years ago
Please Explain me.
Kavipriya said:
7 years ago
I didn't get it. Please explain.
Anomi said:
7 years ago
When will z become true? After the completion of 1 complete loop?
Abbas said:
7 years ago
Anyone, please Explain me to understand.
Hafiz Basam said:
7 years ago
You are right @Azeema, @Aswini, @Gayathri.
y = --x so y=3 this 3 is assigned to x. Now x=3.
z = x-- so z=3 because it is a post-decrement.
After performing the operation x=2.
So, finally, x=2 y=3 z=3.
y = --x so y=3 this 3 is assigned to x. Now x=3.
z = x-- so z=3 because it is a post-decrement.
After performing the operation x=2.
So, finally, x=2 y=3 z=3.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers