+ 1

Array Question

Can someone tell me how the answer in this question is 17? What is the output of this code? int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result);

11th Dec 2018, 8:18 AM
Ky Jovs
Ky Jovs - avatar
4 Answers
+ 5
Hi guys, I just want to point out that there is no +3 in the ensuing calculation during the loop because of the if statement. So it's actually 0+1+2+10+4 = 17 (not 0+1+2+10+3+4 = 20).
11th Dec 2018, 10:24 AM
Lambda_Driver
Lambda_Driver - avatar
+ 4
When i==1: result+=1 //Result=0+1 i==2: result+=2 //Result=1+2=3 i==3: result+=10 //Result=3+10=13 i==4: result +=4 //Result=13+4=17
11th Dec 2018, 1:28 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 1
I'm getting confused. 0+1+2+10+3+4 != 17. I'm really sorry, I am just new to this thing. :(
11th Dec 2018, 8:30 AM
Ky Jovs
Ky Jovs - avatar
0
Ahh, I get it already. LOL
11th Dec 2018, 8:38 AM
Ky Jovs
Ky Jovs - avatar