Algorithm


1. Declare a variable n to store the number till which we need to find the sum.
2. Prompt the user to enter a value for n and store the input in n.
3. Declare a variable sum and initialize it to 0 to store the sum of the numbers from 1 to n.
4. Use a loop to iterate over the numbers from 1 to n, adding each number to sum.
5. After the loop terminates, print the value of sum.

Code Examples

#1 Code Example- C++ Programing Sum of n consecutive numbers without an array(using while loop)

Code - C++ Programming

#include <iostream>
using namespace std;

int main()
{
    int n, sum = 0;
    cout << "Enter number till which you would like to add: ";
    cin >> n;
    while (n > 0)
    {
        sum += n;
        n--;
    }
    cout << "\nSum is: " << sum << endl;
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter number till which you would like to add: 3
Sum is:6

#2 Code Example- C++ Programing Sum of n numbers without an array(using while loop)

Code - C++ Programming

#include <iostream>
using namespace std;

int main()
{
    int n, sum = 0, number;
    cout << "How many numbers do you want to add? ";
    cin >> n;
    cout << "\nEnter numbers: ";
    while (n > 0)
    {
        cin >> number;
        sum += number;
        n--;
    }
    cout << "\nSum is: " << sum << endl;
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
How many numbers do you want to add? 7
Enter numbers:
1
2
3
4
5
89
34
Sum is:138

#3 Code Example - C++ Programing Sum of n numbers in array(using for loop)

Code - C++ Programming

#include <iostream>
using namespace std;

int main()
{
    int n, sum = 0;
    cout << "How many numbers do you want to add? ";
    cin >> n;
    int arr[n];
    cout << "\nEnter numbers: ";
    for (int i = 0; i < n; i++)
        cin >> arr[i];
    for (int i = 0; i < n; i++)
        sum += arr[i];
    cout << "\nSum is: " << sum << endl;
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
How many numbers do you want to add? : 3
Enter numbers:
23
12
54
Sum is:89
Advertisements

Demonstration


C++ Programing Example to Calculate Sum of Natural Numbers-DevsEnv