Question: Consider carefully the program fragment below: int sum = 0, i = 0; while (i < 5) { sum = sum + i; i++; }
Consider carefully the program fragment below:
int sum = 0, i = 0;
while (i < 5)
{
sum = sum + i;
i++;
}
The above loop does at least one unnecessary pass through the body. How can you improve it while not changing the result (the value of sum when the loop ends)?
| A | Initialize the variable sum to 1 rather than 0 |
| B | Initialize the variable i to 1 rather than 0 |
| C | Change the while loop condition from i < 5 to i < 4 |
| D | Change the while loop condition from i < 5 to i <= 4 |
| E | Place the statement i++; before sum = sum + i; rather than after it. |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
