+ 1

I understand the for loop here; I don't understand how the if else works here....

int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println (result); /* The for loop gives 0 1 2 3 4 values; so which do we take*/

27th Nov 2017, 10:07 AM
Rizan
Rizan - avatar
2 Answers
+ 5
inside "{ }" of "if" only run when condition inside "( )" meets. otherwise it will run "else". more explanation: the loop will be 5 times, and "i" will be 0 - 1 - 2 - 3 - 4. this will run 5 times and "i" value base on that increment. if (i == 3) { result += 10; } else { result += i; } there is condition "i == 3", so when "i" is 3, "result += 10;" will run, anything else "result += i;"
27th Nov 2017, 10:22 AM
Andika Romansyah