FOR LOOP

The following code is supposed to calculate the sum of the numbers 2 through 5. That is, it should calculate the value of 2 + 3 + 4 + 5, which is 14. However, there is a logical error in the code. The code gives an answer of 19.

#include <iostream>
using namespace std;

int main()
{int next = 2, sum = 1;
while (next <= 5)
{ next++;
sum = sum + next;
}
cout << "The sum of 2 through 5 is " << sum << endl;
closed account (48T7M4Gy)
Start:
next = 2
sum = 1

next = 3
sum = 1 + 3 = 4

next = 4
sum = 4 + 4 = 8

next = 5
sum = 8 + 5 = 13

next = 6
sum = 16 + 6 = 19
ends while loop

displays value of sum, 19

Last edited on
Thank you!
closed account (48T7M4Gy)
Start:
next = 2
sum = next = 2

next = 3
sum = 2 + 3 = 5

next = 4
sum = 5 + 4 = 9

next = 5
sum = 9 + 5 = 14
ends while loop

displays value of sum, 14
What can i change to get a sum of 14
closed account (48T7M4Gy)
Read the 'trace' carefully @daniel, very carefully ... but there's no magic so don't sweat. Try it yourself. Just imagine you are the computer and write down what happens at each line of your program as you go from step to step.

The bad news to answer your question is "change your program", the good news is "but it doesn't have to be very much". :)
Last edited on
Oh i see, thank you for your help and time.
Topic archived. No new replies allowed.