In the previous article, we have discussed about C++ Program to Check Whether Number is Even or Odd. Let us learn how to Calculate Sum of First N Natural Numbers in C++ Program.
Methods to calculate the sum of first n natural number numbers in c++
In this article, we see how we can calculate the sum of first n natural numbers. There are different methods to achieve this. Let see all the methods one by one.
Method 1-Using for loop
This is one of the methods to achieve this task. We will start a loop from 1 to the given number and add them in a variable and return or print the variable. Let write the code for this.
#include <iostream> using namespace std; int main() { int n=10,i,sum=0; for(i=0;i<=n;i++) { sum+=i; } cout<<sum<<endl; return 0; }
Output
55
Here we find the sum of the first 10 natural numbers and we get the result 55.
Method 2-Using while loop
Instead of using for loop, we can also achieve the same through while loop. The concept will remain same as method 1. Let write the code for this.
#include <iostream> using namespace std; int main() { int n=10,i=1,sum=0; while(i<=n) { sum=sum+i; i++; } cout<<sum<<endl; return 0; }
Output
55
Method 3-Using sum of AP formula
Here we can analyze that instead of using a loop we can also use the concept of Arithmetic Progression(A.P.). Here the common difference will be 1 and we also know the first term which is 1 and the last term which is n so we simply use the A.P. sum formula.
Formula:-n/2(a + l)
Where n is the total terms, a is the first term and l is the last term.
Let’s write the code for this
#include <iostream> using namespace std; int main() { int n=10,a=1,sum=0,l=10; sum=(n*(a+l))/2; cout<<sum<<endl; return 0; }
Output
55
So these are the methods to calculate the sum of first n natural numbers in c++.