C++ Program to calculate the sum of N natural numbers


January 17, 2023, Learn eTutorial
1275

This is a simple C++ program to learn to calculate the sum of n natural numbers.

How can we calculate the sum of n natural numbers?

How we find the Sum of n numbers?

Natural numbers are numbers that include all the whole numbers excluding the number 0.

Natural numbers = { 1, 2, 3, 4, 5…………………..}

In this C++ program, n is the number of natural numbers. So to find the sum of n natural numbers we have to add 1 + 2 + 3 + …….+ n.

For example n = 6
sum = 1 + 2 + 3 + 4 + 5 + 6 = 21

How to write a C++ program for calculating the sum of n natural numbers?

The program takes a positive integer from the user. This value is loaded into the variable ‘n’. A for loop can be used to add n natural numbers.
Syntax offorLoop

Here for our program, the loop will be like this,


for (i = 1; i<= n; i++ )
{ 
   sum +=i; 
}
 

initialize the value of 'i' as 1 and check for the condition 'i<=n'. if the condition is not satisfied then add 'i' with the sum and update the value of the 'sum'. increment the value of 'i' by 1 on each iteration. This process will continue until the condition is true. the final result will be on the variable 'sum'. Print 'sum' and finish the program

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare integer variables; n, sum

Step 5: Print a message to enter a positive integer.

Step 6: Read the number into the variable n.

Step 7: using a for loop find the sum of natural numbers upto n
            Sum = 1+ 2 + 3 +…..+ n;
Step 8: print sum.

Step 9: Exit.
 

C++ 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: 8
Sum = 36