A program to find the sum of first n natural numbers using recursion, where n is entered by the user.

 

#include<iostream.h>
#include<conio.h>

int sum(int n)
{
int result=0;

if(n<1)
return(result);
else
{
result=n+sum(n-1);
return(result);
}
}

void main()
{
clrscr();
int num;

cout<<"Enter a number:";
cin>>num;

cout<<"The sum of the natural numbers is:"<<sum(num);

getch();
}

 

< Back