Can anyone explain this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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😖

9th Dec 2017, 9:28 AM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
14 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.
9th Dec 2017, 9:40 AM
qwerty
qwerty - avatar
+ 19
@ Charan Leo25, thanks, nice 👍
9th Dec 2017, 1:06 PM
tooselfish
tooselfish - avatar
+ 18
a special thanks to Pegasus, nice explanation 👍😉
9th Dec 2017, 10:16 AM
tooselfish
tooselfish - avatar
+ 17
@all, and a thanks from me, i learned too 👍😉
9th Dec 2017, 10:15 AM
tooselfish
tooselfish - avatar
+ 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 :)
9th Dec 2017, 9:36 AM
Dapper Mink
Dapper Mink - avatar
+ 11
Thanks to all😉😉
9th Dec 2017, 9:43 AM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 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😊
9th Dec 2017, 9:44 AM
🌛DT🌜
🌛DT🌜 - avatar
+ 11
Since others explained it already, let me tell you that this is a simple way to execute a+b without actually using +
9th Dec 2017, 9:59 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 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.
9th Dec 2017, 9:39 AM
ifl
ifl - avatar
+ 8
😂😂 A trick
9th Dec 2017, 10:00 AM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 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
10th Dec 2017, 2:19 PM
Pradheepviki😎😀
Pradheepviki😎😀 - avatar
+ 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.
10th Dec 2017, 2:20 PM
Pradheepviki😎😀
Pradheepviki😎😀 - avatar
+ 1
- a steals from b - little by little - as much as it can
10th Dec 2017, 9:57 PM
Pătraşcu Luci
Pătraşcu Luci - avatar
+ 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
11th Dec 2017, 12:06 PM
Я. ♨
Я. ♨ - avatar