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


Correct Option: B

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.

Find more quizzes: