Sum of n natural numbers in C++

Written by

Juhi Kamdar

To get the sum of n numbers, there can be two cases:

  1. Add consecutive n numbers.
  2. Add any n numbers.

Method 1 – Sum of n consecutive numbers without an array(using while loop)

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:

#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;
}

Output:

Enter number till which you would like to add: 3

Sum is:6

Method 2 – Sum of n numbers without an array(using while loop)

Code:

#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;
}

Output:

How many numbers do you want to add? 7

Enter numbers:
1
2
3
4
5
89
34

Sum is:138

Method 3: Sum of n numbers in array(using for loop)

Code:

#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;
}

Output:

How many numbers do you want to add? : 3

Enter numbers:
23
12
54

Sum is:89