Exercise:
Write a C++ program that uses recursive function to find the sum of natural numbers.
Click Here to View the Solution:
#include <iostream>
using namespace std;
int sum(int num);
int main()
{
int num;
cout << "Insert a positive number: ";
cin >> num;
cout << "Its recursive sum is: " << sum(num);
return 0;
}
int sum(int num)
{
if(num != 0)
return num + sum(num - 1);
return 0;
}
Click Here to View the Output:
Insert a positive number: 20 Its recursive sum is: 210
Click Here to View the Explanation:
- This program operated by requesting the user to enter a number
num
. num
is passed tosum ()
function. The sum is saved and added to the answer of the addition result ofnum-1
.num
is decremented by 1.- The process continues until
num
is decreased to 0. - The answer is calculated by returning each addition result.