C++ Program to Calculate Sum of Natural Numbers

Write a C++ program to calculate the sum of natural numbers. To write this program we will use for loop.

The sum of natural numbers is calculated as 1+2+3+4+….+N, or you can directly use formula N(N+1)/2. Using formula developing C++ program is too much easy so lets us develop C++ program using loop to calculate sum = 1+2+3+4+….+N. You can use either for loop or while loop or do-while loop for this purpose.

// C++ program to Calculate sum of Natural numbers
#include<iostream>
using namespace std;
int main()
{
  // declare variable
  int n, i, sum=0;

  // take input
  cout << "Enter the N value: ";
  cin >> n;

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

  // display result
  cout << "Sum= " << sum << endl;

  return 0;
}

Output:-

Enter the N value: 10
Sum= 55

Write a Program to Print First 10 Natural Numbers in C++

// C++ program to Calculate sum of Natural numbers
#include<iostream>
using namespace std;
int main()
{
  // declare variable
  int sum=0;

  // calculate sum
  for (int i = 1; i <= 10; i++)
  {
    sum += i;
  }

  // display result
  cout << "Sum= " << sum << endl;

  return 0;
}

Output:-

Sum= 55

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Learn More C++ Programming Examples,

Leave a Comment

Your email address will not be published. Required fields are marked *