program to calculate the sum of the natural number by using recursion.
In this program we ,we now calculate the sum of natural number using recursion in c-program, taking input positive integer from the user.
Recursion means function calling itself is called recursion.
suppose 15 is passed as an argument to the function fun() ,from the main method . In the fun() function,
subsequently until "if" statement returns the false value ,then the value decrease by one in every step and we added fun(num-1) to num. the statement is doing it until num value is 0. if the num values is 0 ,then the else block gets execute and o is return
Therefore ,function return the value form which where function is call in the main()function.
#include<stdio.h>
int fun(int num);
void main()
{
int n,sum=0;
printf("enter the number\n");
scanf("%d",&n);
sum=fun(n);
printf("the sum of the number is %d",sum);
getch();
}
int fun(int num)
{
if(num==1)
return(1);
else
return(num+fun(num-1));
}
For more c-programming example:-
1.c-program to calculate the sum of the natural number by using recursion
No comments:
Post a Comment