#include <iostream>
usingnamespace 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;
}
#include <iostream>
usingnamespace std;
int main() {
int next {2}, sum {};
while (next <= 5)
sum += next++;
cout << "The sum of 2 through 5 is " << sum << '\n';
}
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).
#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';
}
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>
usingnamespace 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;
}