Multiple choice technology programming languages

What is sum after the following loop terminates? int sum = 0; int item = 0; do { item++; sum += item; if (sum > 4) break; } while (item < 5);

  1. 5

  2. 6

  3. 7

  4. 8

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

The do-while loop executes at least once. Iteration 1: item becomes 1, sum becomes 1. Iteration 2: item becomes 2, sum becomes 3. Iteration 3: item becomes 3, sum becomes 6. Now sum > 4, so break executes. Loop terminates. Final sum is 6.

AI explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) 5 - This option is incorrect because the loop will continue until the value of item is 5, and the sum at that point will be 6.

Option B) 6 - This option is correct. Let's break down the loop execution:

  • Initially, sum is 0 and item is 0.
  • In the first iteration, item is incremented to 1, and sum is updated to 1.
  • In the second iteration, item is incremented to 2, and sum is updated to 3 (1 + 2).
  • In the third iteration, item is incremented to 3, and sum is updated to 6 (3 + 3).
  • Since sum is now greater than 4, the loop terminates.

Option C) 7 - This option is incorrect because the loop terminates when the sum is greater than 4, which happens at sum = 6 as explained above.

Option D) 8 - This option is incorrect because the loop terminates when the sum is greater than 4, which happens at sum = 6 as explained above.

The correct answer is B) 6. This option is correct because the loop terminates when the sum is greater than 4, and at that point, the sum is 6.