0

(Arrays) Module 3 Quiz - Second question

Hi, I can't seem to figure out why the answer to the second question is 17. This is the code: 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); Could someone explain this? Thanks in advance!

30th Oct 2017, 10:29 PM
Wesley Kater
Wesley Kater - avatar
3 Answers
+ 9
first interaction: i = 0 result += i => result = 0 second interation: i = 1 result += I => result = 1 third iteration I = 2 result => 1 + 2 => 3 fourth iteration I = 3 if ( I == 3) result += 10 result = 3 + 10 => result = 13 fifth iteration I = 4 result = 13 + 4 => result = 17 don't get confused I is the same as i, my auto correction is stupid :P
30th Oct 2017, 10:34 PM
Kamil
Kamil - avatar
+ 1
Hi I don't understand that for 1st question why the answer is 2. I don't understand this code at all. Question What is the output of this code? int arr[] = new int[3]; for (int i=0; i<3; i++) { arr[i] = i; } int res = arr[0] + arr [2]; System.out.println(res);
6th May 2022, 12:34 PM
Nanduni Jayasuriya
Nanduni Jayasuriya - avatar
0
Ah, clear explanation, does makes sense now! Thanks for the answer :).
30th Oct 2017, 10:42 PM
Wesley Kater
Wesley Kater - avatar