Calculating the sum of natural numbers is a fundamental programming problem that can be easily solved using C++ programming language.
In this tutorial, we will demonstrate how to write a simple program to calculate the sum of natural numbers using C++.
To begin, we need to understand what natural numbers are. Natural numbers are a set of positive integers that start from 1 and go on indefinitely.
In other words, natural numbers are 1, 2, 3, 4, 5, and so on. The sum of the first n natural numbers is given by the formula:
sum = 1 + 2 + 3 + … + n = n(n+1)/2
Now, let’s write a C++ program that calculates the sum of natural numbers up to a given limit.
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter the value of n: ";
cin >> n;
for(int i=1; i<=n; i++)
{
sum += i;
}
cout << "The sum of first " << n << " natural numbers is: " << sum << endl;
return 0;
}
In the above program, we first declare two integer variables, n and sum, to store the input and the sum of natural numbers, respectively.
We then prompt the user to enter the value of n using the cout and cin statements.
Next, we use a for loop to iterate through the natural numbers from 1 to n. Inside the loop, we add each number to the variable sum.
Finally, we use the cout statement to display the result of the sum of the first n natural numbers.
That’s it! This simple program should give you an output of the sum of natural numbers for a given limit.
In conclusion, C++ is a powerful programming language that allows you to perform various arithmetic operations.
The program we demonstrated in this blog post is a basic example of how to use C++ to calculate the sum of natural numbers.




