Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started