In this tutorial, we will discuss a concept of C++ program to find the sum of natural numbers using recursion
In this article, we are going to learn how to find the sum of natural numbers using recursion in the C++ programming language
The positive integer numbers 1,2,3,4….n are known as natural numbers
Program
This program allows entering a number to find the sum of natural numbers from 1 to given number using the recursive function in C++ programming language.
#include <iostream> #include <conio.h> using namespace std; int addNumbers(int); //function Prototype int main() { int num; //variable declaration cout<<"enter a positive integer find sum: "; cin>>num; cout<<"Sum of natural numbers are until "<<num<<":"<<addNumbers(num); //functiuon call getch(); return 0; } int addNumbers(int n)//function definition { if(n!= 0) return n+addNumbers(n-1); else return n; }
When the above code is executed, it produces the following results
Enter a positive integer to find sum: 25 Sum of natural numbers are until 25: 325
In the above program , the number entered by the user is passed to the addNumber() function as an argument.
In the above case, when the user enters 25 as an argument, 25 is passed to function. Subsequently, until “if” statement returns the true value, value decreases by one in every step. Finally, when the value becomes 0, “if” statement returns as false and the “else” part is executed.
Therefore, function return with decreasing value to calculate the result e.g 1+2+3+4+5…..24+25=325
Similar post
Java program to find the sum of natural numbers using loops
Python program to Calculate the sum of natural numbers using loops
C++ program to calculate the sum of natural numbers using loops
C program to calculate the sum of natural numbers using loops
Java program to find the sum of natural numbers using recursion
Python program to Calculate the sum of natural numbers using recursion
C program to calculate the sum of natural numbers using recursion
Suggested for you
10 simple ways to add two numbers in Java In this article, we will discuss…
Write a Python program to find the first n prime numbers In this article we…
Python: Calculate Average of odd and even in a list using loops In this post,…
Python: Average of Odd & Even Numbers from User Input In this post, we will…
Explanation of one dimensional array In this post, we will discuss the concept of "Explanation…
Python program to calculate the sum of odd and even numbers in a list In…