+ 1

loops

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 did not get it someone explain it to me

9th Apr 2020, 10:26 PM
Ahmed Hesham
Ahmed Hesham - avatar
6 Respostas
+ 4
Ahmed Hesham The output is 17. Result is initially 0. It keeps increasing in the for loop. for(int i = 0; i < 5; i++){ result gets added to i after each iteration unless i has reached the iteration of 3, in that case add 10. } So in this range, i is first 0 i is not equal to 3 so 10 wouldn't be added but i would be added so result = result + 0 Then i is 1 (coz its for loop, i is incrementing by 1) again result += 1 Then, result += 2 Now i = 3, so result += 10 would happen. Then result += 4 coz now i = 4.
9th Apr 2020, 10:54 PM
maf
maf - avatar
+ 6
0: result is 0 1: result is 1 2: result is 3 3: result is 13 4: result is 17 5: exit Finally result is 17
9th Apr 2020, 10:49 PM
Marina Vasilyova
Marina Vasilyova - avatar
+ 3
I think the answer will be 1 2 3 14 5 As i iterates through the loop from 0 to 4, (<5) it checks the conditions before printing the result. i0 +1 = 1 i1 +1 = 2 i2 +1 = 3 i3 + 1 = 14 i4 + 1 = 5
9th Apr 2020, 10:45 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Maria Vasilyova, maf I see my mistake, thanks guys
9th Apr 2020, 11:29 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Maria Vasilyova, maf Thanks , now i understand it , well explained maf
10th Apr 2020, 4:58 PM
Ahmed Hesham
Ahmed Hesham - avatar
0
10th Apr 2020, 5:00 PM
maf
maf - avatar