Coders Packet

Sum of all numbers till n using Recursion in CPP

By Rahul Chandrakant Suthar

In this project, we will discuss how to use Recursion in CPP language to get the sum of all numbers to n.

For example, if we want to calculate the sum of the numbers preceding the number 5, it will be 0 + 1 + 2 + 3 + 4 + 5 which will give us 15.

We can follow these approaches to find the sum of all numbers to n,

  1. Sum till n = n + n-1 + n-2 + n-3 …….+ 1
  2. Sum till n = n + sum till n-1.
  3. Sum till n-1 = n-1 + sum till n-2.

So, in these, we divide our problem into subproblems.
As an example, in the first, we calculate the sum of all values, and in the second, we calculate the sum until n-1 and then add it to n.
And for the sum up to n-1, we calculate the sum up to n-2 and then add it to the n-1.

Recursion Example

This is known as recursion, which means when a function calls itself until an endpoint or break condition is reached.

This calling of Function must now be broken. So we used a Breaking Condition, and the Breaking Condition is Sum till 0 = 0 because we know that Sum till 0 will always be zero.

Example of breaking Condition in C++

if(n==0){
  return 0; // if the n is 0 then it will return 0 and it will break the recursion
}

So to solve this problem we will create a function Sum in which
If the user sends N then it will call function (n-1), then (n-1) should call function(n-2), and so on.

So for Example We will create a function in our code like this

recursion 2 example

 

To understand the Logic of Sum(n-1)

So, if we pass N -1 to the function, it will call Sum(n-1-1) which is Sum (n-2)

Recursion Example

and if Sum(n-2) is passed to the function then it will call Sum(n-3) and so on.

Now the Execution part.

#include 
using namespace std;
int Sum(int n){
    if(n==0){
        return 0;
    }
    int prevSum = Sum(n-1);
    return n + prevSum;
}
int main(){
    int n;
    cout<<"Enter Number"<<endl;
    cin>>n;
    cout<<Sum(n);

    return 0;
}

 

 

Input

The number entered by the user is 5.

         

Output

Output is 15 as expected.

         

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Rahul Chandrakant Suthar (Rahulcs27)

Download packets of source code on Coders Packet