Error spotting

Hey all. Am working on a program. Being new to C++, am unable to spot errors in the program that I have written. The program is supposed to display the addition of numbers from 2 to five that is [2+3+4+5] https://www.theengineeringprojects.com/2021/11/data-structures-in-c.html

Any leads to this solution is highly welcomed.

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;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main ()
{
    int next = 2 ;
    int sum = 0 ; // 1; // initialise sum to zero

    while (next <=5)
    {
        sum = sum + next; // add next to sum before incrementing next
        next++;
    }

    std::cout << "The sum of 2 through 5 is " << sum << '\n' ;
}
Using the strandard mathematical result for the sum of consecutive integers, you can do:

1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
	constexpr int n { 5 };

	std::cout << "The sum of 2 through " << n << " is " << n * (n + 1) / 2 - 1 << '\n';
}



The sum of 2 through 5 is 14

Topic archived. No new replies allowed.