What is the answer of the following code snippet and explain how you get the answer | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the answer of the following code snippet and explain how you get the answer

What is the output of this code? int result = 0; for (int i = 0; i < 5; i++) { if (i == 3) { result += 10; } else { result += i; } } System.out.println(result);

27th Nov 2019, 10:23 AM
Brian Shumba
Brian Shumba - avatar
3 Answers
+ 12
Initially the value of result = 0 ➡️ Now for i=0, the if i==3 condition is false, so result = 0+0 i.e. result will be zero ➡️ Now for i=1, the if==3 condition is false, so result = 0+1 i.e. result will be 1. ➡️ Now for i=2, the if ==3 condition is again false, so result = 1+2 i.e. result will be 3. ➡️ Now for i=3, the if condition will be true as I==3 is true so the value of result will be 3+10 = 13 ➡️ Now for i=4, the if condition is false, so result = 13+4 i.e. result will be 17. ➡️ Now the loop stops iterating as i<5 condition is false. So it comes out of the loop and print the value of result i.e. 17. Hope this is helpful 😅
27th Nov 2019, 10:38 AM
Nova
Nova - avatar
+ 2
For i=0 : i != 3 , so (result += 10) will not be executed , we skip to the else statement : result += i : so result = 0+0 = 0. For i=1 , the same case , we execute the else statement : so result=0+1 = 1 For i=2 , result = result + i = 1 + 2 => result = 3 For i=3 , the condition is verified here , so we execute ( result +=10 ) => result = 3+10 = 13 For i=4 , result = result + 4 => result = 17 For i=5 , the loop' condition i<5 is not verified , then the end of the loop. The output is : 17
27th Nov 2019, 10:50 AM
Meriem Es-saghir
+ 2
thank you very much it all make sense now
27th Nov 2019, 12:58 PM
Brian Shumba
Brian Shumba - avatar