Recursion Examples Set 1
Set 1 Set 2 Set 3
Question :1
Write a program in C langauge to calculate and print factorial of a number using recursion?
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
if (n==0)
return(1);
else
return(n*fact(n-1));
}
int main()
{
int n,f;
printf(“Enter any number “);
scanf(“%d”,&n);
f=fact(n);
printf(“the factorial of the number %d is %d \n”,n,f);
return(0);
}
Question : 2
Write a program in C langauge to calculate and print sum of all the numbers upto the limit using recursion?
#include<stdio.h>
#include<conio.h>
int sum(int n)
{
if (n==0)
return(0);
else
return(n+sum(n-1));
}
int main()
{
int n,s;
printf(“Enter any limit number “);
scanf(“%d”,&n);
s=sum(n);
printf(“the sum of the first %d numbers is %d \n”,n,s);
return(0);
}