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?
7 Antworten
+ 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
+ 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
+ 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);
}
}
+ 2
thanks #AJ and #Shruthi let me try.
+ 1
#AJ thanks for clarifying me great explanation 👏👏👏
+ 1
AJ Anant ok genius 🤙
0
faakeer use @ before name to tag someone.