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);
-
5
-
6
-
7
-
8
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.
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,
sumis 0 anditemis 0. - In the first iteration,
itemis incremented to 1, andsumis updated to 1. - In the second iteration,
itemis incremented to 2, andsumis updated to 3 (1 + 2). - In the third iteration,
itemis incremented to 3, andsumis updated to 6 (3 + 3). - Since
sumis 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.