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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!