+ 2

I don't understand the answer

What is the output of this code? var result = 0; for var i = 0; i < 5; i++ { if i == 3 { result += 10; } else { result += i; } } print(result) (the result is 17 but I dont understand why)

12th May 2017, 4:34 PM
Janet Hamrani
2 Answers
+ 22
i = 0 => result += 0 => result = 0 + 0 = 0 i = 1 => result += 1 => result = 0 + 1 = 1 i = 2 => result += 2 => result = 1 + 2 = 3 i = 3 => result += 10 => result = 3 + 10 = 13 i = 4 => result += 4 => result = 13 + 4 = {17}
12th May 2017, 4:36 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 8
The loop will run 5 times until i = 5; Loop one for i = 0 : result = result + i; result  = 0 + 0; result  = 0; Loop two for i = 1: result = result + i; result  = 0 + 1; result = 1 Loop three for i = 2 : result = result + i; result  = 1 + 2; result = 3; Loop four for i = 3 : result  = result + 10; result = 3 + 10; result  = 13; Loop five for i = 4; result  = result + i; result  = 13 + 4; result  = 17; In  loop four for the if statement, when i == 3 we have to add 10 to the result.
12th May 2017, 5:12 PM
Apel Mahmod
Apel Mahmod - avatar