codescracker
c++

C++ Program to Find and Print Sum of First n Natural Numbers



« C++ Tutorial C++ Example »

This article is created to provide some programs in C++ that find and prints the sum of first n natural numbers. The value n must be entered by user at run-time. The program is created in following ways:

Note - Natural number starts with 1 and continues like 1, 2, 3, ....

Find Sum of First n Natural Numbers using while Loop

The question is, write a program in C++ that receives the value of n and print the sum of first n natural numbers. Here is its answer:

#include<iostream>
using namespace std;

int main()
{
   int n, natural=1, sum=0;
   cout<<"Enter the Value of n: ";
   cin>>n;
   while(natural<=n)
   {
      sum = sum+natural;
      natural++;
   }
   cout<<"\nSum of First "<<n<<" Natural Numbers = "<<sum;
   cout<<endl;
   return 0;
}

Here is the initial output produced by above C++ program on finding and printing the sum of n natural numbers:

c++ find sum of n natural numbers

Now supply the number say 10 as the value of n and press ENTER key to find sum of first 10 natural numbers like shown in the snapshot given below:

find sum of first n natural numbers c++

Find Sum of First n Natural Numbers using for Loop

This program is created using for loop, instead of while.

#include<iostream>
using namespace std;

int main()
{
   int n, natural, sum=0;
   cout<<"Enter the Value of n: ";
   cin>>n;
   for(natural=1; natural<=n; natural++)
      sum = sum+natural;
   cout<<"\nSum of First "<<n<<" Natural Numbers = "<<sum;
   cout<<endl;
   return 0;
}

Here is its sample run with user input 12:

sum of first n natural numbers c++

Find Sum of First n Natural Numbers using Function

This is the last program created using a user-defined function named myfun() that takes an integer say n as its argument, then find and return the sum of first n natural numbers.

#include<iostream>
using namespace std;

int myfun(int);
int main()
{
   int n, sum;
   cout<<"Enter the Value of n: ";
   cin>>n;
   sum = myfun(n);
   cout<<"\nSum of First "<<n<<" Natural Numbers = "<<sum;
   cout<<endl;
   return 0;
}
int myfun(int n)
{
   int natural, sum=0;
   for(natural=1; natural<=n; natural++)
      sum += natural;
   return sum;
}

C++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker