C++ Program to Find the Sum of First N Natural Numbers

sum of first n natural number in c++

Program to find sum of first  N natural numbers

We know that Natural number is integer number which start from 1,2,3,4…… and so on.

So we will calculate the First N natural number

In the sum of first N natural number user gave the value of N. If the value is 6 then process is following

1+2+3+4+5+6 = 21

Here we will see two different methods to do find sum of first n natural numbers. One is by using formula whose time complexity is O(1) and other is by using for loop whose time complexity is O(n).

Method 1

Algorithm

  • Step 1. Start
  • Step 2. Enter a number (N).
  • Step 3. Use formula to calculate the sum of N natural number || Sum=(n*(n+1))/2.
  • Step 4. Print sum of N Natural Number.
  • Step 5. Stop

C++ Code

#include
using namespace std;
int main()
{
  //Declare variable sum and n
  int sum = 0, n;

  //Take input from user
  cout<<"Enter the first N Natural Number\n"; cin>>n;
  
  //Apply formula to find answer
  sum=(n*(n+1))/2;
  
  //Print answer
  cout<<"Sum is "<<sum;
  
  //End of program
  return 0;

}

Output

Enter the first N Natural Number
3
Sum is 6

 

Time complexity

The time complexity of this program is O(1).

Auxiliary Space

The auxiliary space of this program is O(1)

Formula used

We have used formula (n*(n+1))/2 to find answer in O(1). 

Let n=3

sum=1+2+3=6

Using formula : (3*4)/2=12/2=6

Hence we are getting same answer using formula as well.

 

Method 2

Algorithm:-

Step 1 : Ask the user to enter a  number which will denote the limit.

Step 2 : Declare a variable to store the addition and initialize it with 0.

Step 3 : Use a loop to perform iterations for adding natural numbers from 1 till the limit entered by the user.

Step 4 : Use a statement for addition purpose.

Step 5 : Print the result.

C++ Code:-

#include
using namespace std;
int main() 
{ 
    //for initialize variable
    int Number, i, Sum = 0;
    //to take user input
    cout<<"\n Kindly Insert an Integer Variable\n"; cin>>Number;

    //use for loop for these condition
    for(i = 1; i <= Number; i++)
    {
       Sum = Sum + i;
    }

    //display
    cout<<"Sum of Natural Numbers: "<< Sum;

    return 0;
}

Output

Kindly Insert an Integer Variable
4
Sum of Natural Numbers: 10

 

Time complexity

The time complexity of this program is O(n).

 

Auxiliary Space

The auxiliary space of this program is O(1)