+ 1
how come output of below code is 24? int i=1; while(++i <=5) printf("%d",i++);
6 odpowiedzi
+ 7
its 2 4 and not 24, first iteration ++i i become 2, and 2 is printed then i++ i get incremented to 3 (post and pre increment) ++i i becomes 4, 4 get printed, i++ i is incremented to 5 ++i i incremented to 6 which is not less than or equal to 5
+ 5
Let me first make clear 24 is not single number. It's 2 and 4 immediately printed after 2.
i variable is initially 1.
In while loop we will check if ++i is less than or equal to 5 or not.
If it's then loop continues else stops.
●First iteration.
In while(++i<=5) it's similar to (2<=5) which is true so control enters in loop.
Inside loop: printf("%d",i++); first prints value of i (2) abd then increment it (3).
●Second iteration.
In while(++i<=5) condition is similar to (4<=5) which is true.
So it enters in loop and like before prints value of i that is 4 and then by incrementing makes it 5.
●Third iteration
In while(++i<=5) is similar to
(6<=5) which results in false. So actually loop don't get executed and stops.
Hence result is 24 ie. Actually 2 and 4...
+ 5
End note 📝 :
●Please learn about prefix and postfix increment /decrement operator.
Just an overview :
*Postfix.:
int i=3;
printf("%d",i++);
Result in 3 not 4 because it first uses value then increments. After this value of i will be 4.
*Prefix: int i=3; printf("%d",++i); this outputs 4 and also value of i will be 4 after this statement.
https://www.programiz.com/article/increment-decrement-operator-difference-prefix-postfix
https://stackoverflow.com/questions/7031326/what-is-the-difference-between-prefix-and-postfix-operators
+ 4
That's right. There is no space between the 2 and 4.
+ 2
thanks all for your help. you cleared my doubt
0