C++ Program calculate the sum of natural numbers.

To understand this Program to Calculate Sum of Natural Numbers, you should have the knowledge of 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 the user( suppose the user entered n ) then, this program displays the value of 1+2+3+….+n.
Numbers 1, 2, 3, …., n are known as natural numbers. This program takes the value of n and finds the sum of first n natural numbers.
For example, If user enters 5 as the value of n then the sum of first n(n=5) natural numbers would be:
1+2+3+4+5 = 15

1- Sum of Natural Numbers using Formula

The formula to find the sum of first n natural numbers is as follows.
sum = n(n+1)/2
The program to calculate the sum of n natural numbers using the above formula is given as follows.

Source Code

#include<iostream>
using namespace std;
int main() { 
   int n=5, sum;
   sum = n*(n+1)/2;
   cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0; 
}


2- Sum of Natural Numbers Using for loop.

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

Post a Comment

 
Top