+ 1

Why the result is 17?

ublic class main { public static void main(String[] args) { int result = 0; for(int i = 0; i <5; i++){ if(i==3) { result += 10; }else{ result += i; } } System.out.println(result); } }

21st Oct 2017, 11:31 AM
Michał Dobiosz
Michał Dobiosz - avatar
2 odpowiedzi
+ 5
1. Run: i = 0 -> 0 + 0 = 0 2. Run: i = 1 -> 0 + 1 = 1 3. Run i = 2 -> 1 + 2 = 3 4. Run i = 3 -> if-clause is now true -> 3 + 10 = 13 5. Run i = 4 -> if-clause is false again -> 13 + 4 = 17 Now i is 5, therefore the loop terminates because the statement isnt true anymore. And the final result is 17.
21st Oct 2017, 11:36 AM
Shadow
Shadow - avatar
+ 9
when i is 1,2,4, it has been added to result. result = 1+2+4 = 7 when i is 3, 10 is added. result = 7+10 = 17
21st Oct 2017, 11:36 AM
Shamima Yasmin
Shamima Yasmin - avatar