Sum of natural numbers in C++

We will take a number as input from the user and then determine the sum of natural numbers less than or equal to that numbers. Suppose a user gives the number 7. Then we will determine sum of,

1,  2,  3,  4,  5,  6 and 7.

We can make the program to determine the sum in several way. We will see some programs related to determining sum of natural numbers.

Sum of natural numbers using formulae

We can easily make a program to find sum of natural numbers using the formulae bellow;

sum-of-natural-numbers-in-c-300x113

Let’s see the C++ code for determining the sum of numbers using this formulae

// C++ program to find sum of natural numbers

#include <iostream>
using namespace std;

int main(){
    int num, result;

    cout <<"Enter an integer here : ";
    cin >>num;

    result = (num * (num + 1)) / 2;

    cout <<"\nSum is = " << result <<endl;

    return 0;
}

Output of sum of natural number program

sum-of-natural-numbers-program-by-c

Sum of natural numbers using a loop

The bellow program will calculate the sum of natural numbers using a for loop. You can use other loop where the logic may be same or different if you have your own algorithm. Now, let’s see the program.

// sum of natural numbers using for loop

#include <iostream>
using namespace std;

int main(){
    int c, num, result = 0;

    cout <<"Enter the number here : ";
    cin >>num;

    for(c = 1; c <= num; ++c){
        result = result + c;
    }

    cout <<"\nSum is = " <<result <<endl;

    return 0;

}

Output of this program:

Enter the number here : 30

Sum is = 465

Previous pageFind factors

Next pageJump to C++ Practice Section