C++ Program to Find the Sum of Natural Numbers using Recursion

In this post, you will learn how to Display Factors of a Number in C++ programming language.

This lesson will teach you how to Display Factors of a Number, with a recursion statement, mathematical operations and if statement using the C++ Language. Let’s look at the below source code.

How to Display Factors of a Number?

RUN CODE SNIPPET

Source Code

#include <iostream>
using namespace std;
int recurSum(int n)
{
    if (n <= 1)
        return n;
    return n + recurSum(n - 1);
}
int main()
{
    int n;
    cin>>n;
    cout<<"Enter a positive number: "<<n<<endl;
    cout << "\nThe sum of first "<<n<<" numbers is: "<<recurSum(n);
    return 0;
}

Input

6

Output

Enter a positive number: 6
The sum of first 6 numbers is: 21

The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.

  1. When function is called within the same function, it is known as recursion. In this program we find out the sum of the first n numbers, using recursion.
  2. In this code we have two sections, in the first one we declare the function int recurSum(int n) to initiate the recursive function, where we declare the variable n as an integer.
  3. Using the if statement assign the condition to verify if the value of n is greater than or equal to 1. Then return the value of n and perform the function return n + recurSum(n - 1) .
  4. Here the value of recursum holds the range of the numbers used in the execution. The execution starts by default with 1 (n). The value is verified with the if condition, when the condition is true the value is returned using the return function and is used in the mathematical function return n + recurSum(n - 1) .
  5. The function is repeated with the recursion function till the condition is not true.
  6. The function then moves to the output section of the code, where we use output statements to display the answer stored in recurSum(n).

Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you will learn how to Generate Multiplication Table using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Display Fibonacci Sequence using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Find GCD of two Numbers using C++ programming language. This lesson will...
  • C++
  • January 30, 2022