+ 17
Can anyone explain this?
int a=5; int b=4; while (b--!=0){++a } System.out.println(a); Output is 9. Please explain it😖
18 Answers
+ 24
In the while loop:
4 != 0 so a = 6
3 != 0 so a = 7
2 != 0 so a = 8
1 != 0 so a = 9
and when b reaches 0, it stops the while loop.
+ 19
@ Charan Leo25, thanks, nice 👍
+ 18
a special thanks to Pegasus, nice explanation 👍😉
+ 17
@all, and a thanks from me, i learned too 👍😉
+ 16
This algorithm prints the sum of a and b (as long as those are positive integers).
While b is not equal to 0, it adds 1 to a and substracts 1 to b. So when b will be equal to 0, 1 would have been subtracted from b b times, and 1 would have been added to a b times, which is a+b :)
+ 11
Thanks to all😉😉
+ 11
for b=4 --> a=6. decrementing --
b=3 --> a=7
b=2 --> a=8
b=1 --> a=9
b=0 (!=0 condition is false) so while loop will not run so output is 9.
I hope this helps😊
+ 11
Since others explained it already, let me tell you that this is a simple way to execute a+b without actually using +
+ 8
in each iteration of the loop, b is decremented by 1and a is incremented by 1.
when b reaches 0, the loop stops.
since b started at 4, a has been incremented 4 times so the value of a is 9.
+ 8
😂😂 A trick
+ 4
if(--b!=0){
++a;
b should first decrease the value then only check the condition.
o/p is 8
but here taken the b value to check the condition then only decrement the value.
o/p is 9
+ 4
--b means decrement the value by 1 after only check the condition.
b++ means check the condition after only decrement the value by 1.
+ 1
- a steals from b
- little by little
- as much as it can
+ 1
4 != 0, a = ++a = 6
3 != 0, a = ++a = 7
2 != 0, a = ++a = 8
1 != 0, a = ++a = 9
0 != 0, condition false
prints a = 9