+ 2

arrays

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); i dont understand the answer the answer is 17??

4th Jun 2018, 10:11 AM
Jamshid Umarov
Jamshid Umarov - avatar
5 Answers
+ 6
+= adds the current value to any existing values so say result equals 3 and int i = 3 once it reaches the if statment result += 10 would mean that result would now equal 13 next loop would make int i equal 4 += this to result gets you 17
4th Jun 2018, 10:23 AM
D_Stark
D_Stark - avatar
+ 2
It's a for lop that adds to result based on the value of i. When i=0: i == 3 is false so it executes results += i; Thus results = 0 + i==> results += 0 + 0==> results = 0. When i=1: i == 3 is false so it executes results += i; Thus results = 0 + i==> results += 0 + 1==> results = 1. When i=2: i == 3 is false so it executes results += i; Thus results = 1 + i==> results += 1 + 2==> results = 3. When i=3: i == 3 is true so it executes results += 10; Thus results = 3 + 10==> results = 13. When i=4: i == 3 is false so it executes results += i; Thus results = 13 + i==> results += 13 + 4==> results = 17. The for loop ends here because when i = 5, the condition (i < 5) returns false and hence the loop ends.
4th Jun 2018, 10:27 AM
Andre Daniel
Andre Daniel - avatar
+ 1
1.first step i=0; 0<5 is true so it skips if statement since i is 0 now result =result+0=0 2. i = 1; 1<5 else statement is executed result =0+1 = 1 3. i = 2; 2< 5 so else statement is executed . result = 1+2 =3 4.i = 3; 3<5 here if statement (i==3) is executed ie. result = 3+ 10 so 13 5.next i value is 4 so 4 is added result =17 next i vlaue is 5 but condition is not satisfied i< 5 so it comes out of loop and prints result as 17 ..hope u understood
4th Jun 2018, 10:23 AM
Bugs-bunny
Bugs-bunny - avatar
+ 1
result gets added by i in every iteration, except for i==3, where it gets added by 10 i=0: 0 (0+0) i=1: 1 (0+1) i=2: 3 (1+2) i=3: 13 (3+10) i=4: 17 (13+4) i=5: loop condition is wrong, loop terminates
4th Jun 2018, 3:35 PM
Matthias
Matthias - avatar
+ 1
iteration 1: i = 0, result = 0 iteration 2: i = 1, result = 1 iteration 3: i = 2, result = 3 iteration 4: i = 3, result = 13 iteration 5: i = 4, result = 17
4th Jun 2018, 8:24 PM
Ulisses Cruz
Ulisses Cruz - avatar