0

Java Array

int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result); //output 17 1. Can someone explain to me the mechanism of this code?

14th Mar 2020, 6:34 AM
faakeer
faakeer - avatar
7 Respostas
+ 5
It's easy. Here i start with 0 so on first iteration if condition will not satisfy because i == 3 means 0 == 3 is false. So it will go in else condition where result = result + i means result = 0 + 0 = 0. Same for i = 1, 1 == 3 false so result = 0 + 1 = 1 for i = 2, 2 == 3 false so result = 1 + 2 = 3 for i = 3, 3 == 3 true so result = 3 + 10 = 13 for i = 4, 3 == 4 false so result = 13 + 4 = 17
14th Mar 2020, 6:43 AM
A͢J
A͢J - avatar
+ 4
i = 0 then result = 0+0 = 0 i = 1 then result = 0+1 = 1 i = 2 then result = 1+2 = 3 i = 3 inside if => result = 3+10 = 13 i = 4 then result = 13+4 = 17 // output = 17
14th Mar 2020, 6:41 AM
Shruti
Shruti - avatar
+ 2
faakeer To understand mechanism just do like this. Here result += i means result = result + i. int result = 0; for (int i = 0; i < 5; i++) { System.out.println("i = " + i); System.out.println(i == 3); if (i == 3) { result += 10; System.out.println("--if part--" + result); } else { result += i; System.out.println("--else part--" + result); } }
14th Mar 2020, 6:52 AM
A͢J
A͢J - avatar
+ 2
thanks #AJ and #Shruthi let me try.
14th Mar 2020, 6:54 AM
faakeer
faakeer - avatar
+ 1
#AJ thanks for clarifying me great explanation 👏👏👏
14th Mar 2020, 7:10 AM
faakeer
faakeer - avatar
+ 1
AJ Anant ok genius 🤙
14th Mar 2020, 7:13 AM
faakeer
faakeer - avatar
0
faakeer use @ before name to tag someone.
14th Mar 2020, 7:12 AM
A͢J
A͢J - avatar