Can someone help me spot the error?

Oct 4, 2021 at 10:03am
below program should display. The sum of 2 through 5 is 14 ( 2 + 3 + 4 + 5)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;



    return 0;
}
Oct 4, 2021 at 10:14am
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main() {
	int next {2}, sum {};

	while (next <= 5)
		sum += next++;

	cout << "The sum of 2 through 5 is " << sum << '\n';
}



The sum of 2 through 5 is 14

Oct 4, 2021 at 10:23am
@Anonomys,
in your code change:
1
2
    int next = 2 , sum = 1;
    while (next <= 5)

to
1
2
    int next = 2, sum = next;
    while (next < 5)


It would be perverse to start the sum with a value different from the starting point, and your current loop control means that you would go "one beyond" that intended (because you tested for legitimacy before you incremented).
Oct 4, 2021 at 10:28am
Compare your result with
1
2
3
4
5
    while (next <=5)
    {
        sum = sum + next;
        next++;  // do this after you use next in a calculation.
    }


Then compare with
1
2
3
4
for ( next = 2 ; next <= 5 ; next++ )
{
        sum = sum + next;
}

Oct 4, 2021 at 10:40am
Or don't bother with a loop:
1
2
3
4
5
6
#include <iostream>
int main ()
{
   int a = 2, b = 5;
   std::cout << "The sum of " << a << " through " << b << " is " << ( b - a + 1 ) * ( a + b ) / 2 << '\n';
}
Oct 4, 2021 at 12:04pm
From your code ;
initialise sum to 0; ------ [line 8]
the statements in [line 11] and [line 12] must be swapped because one must first compute the value of sum and then next is incremented...

So the correct code will be

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main ()

{
    int next = 2 , sum = 0;
    while (next <=5)
    {
        sum = sum + next;
        next++;
    }
    cout << "The sum of 2 through 5 is " << sum << endl;
    return 0;
}
Topic archived. No new replies allowed.