C++ for Beginners: C++ Program to Calculate Sum of Natural Numbers

(C++ programming Example for Beginners)

C++ Program to Calculate Sum of Natural Numbers

In this example, you’ll learn to calculate the sum of natural numbers.

To understand this example, you should have the knowledge of the following C++ programming topics:

  • C++ for Loop

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.


Example: Sum of Natural Numbers using loop


#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.

This program can also be done using recursion.

 

C++ for Beginners: C++ Program to Calculate Sum of Natural Numbers

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.