fastread homefastrread library fastread menu

C++ : Calculate Sum of Natural Numbers

Tutorial by:Manisha Dubey      Date: 2016-06-18 04:15:08

❰ Previous Next ❱

Positive integers 1, 2, 3, 4... are known as natural numbers. This program takes a positive integer from user( suppose user entered n ) then, this program displays the value of 1+2+3+....+n.

Source Code

#include <iostream>
using namespace std;

int main() {

    int n, sum = 0;
    cout << "Enter a positive integer: ";
    cin >> n;
    for (int i = 1; i <= n; ++i) {
        sum += i;
    }
    cout << "Sum = " << sum;
    return 0;
}

Output

Enter a positive integer: 50
Sum = 1275

 

 
 

This program assumes that user always enters positive number. If user enters negative number, Sum = 0 is displayed and program is terminated.

❰ Previous Next ❱


C++

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website