Recursion Examples
Recursion Examples
Example:1
C Program to calculate and print factorial of a number using recursion?
Sol:

Example:2
C Program to calculate and print factorial of a number using recursion?
Sol:

#include<stdio.h>
int fact(int n); /* function declaration */
int main()
{
int n,f;
printf("Enter any number ");
scanf("%d",&n);
f=fact(n); /* function calling */
printf("the factorial of the number %d is %d \n",n,f);
return(0);
}
/* function definition */
int fact(int n)
{
if (n==0)
return(1);
else
return(n*fact(n-1));
}
Example:2
C program to calculate and print sum of all the numbers upto a specified limit using recusion?
Sol:

#include<stdio.h>
int sum(int);/* function declaration */
int main()
{
int n,s;
printf("Enter any limit number ");
scanf("%d",&n);
s=sum(n);/* function calling */
printf("the sum of the first %d numbers is %d \n",n,s);
return(0);
}
/* function definition */
int sum(int n)
{
if (n==0)
return(0);
else
return(n+sum(n-1));
}
Example:3
C program to calculate and print product of all the numbers up to a specified limit using recursion?

#include<stdio.h>
int prod(int); /* function declaration */
int main()
{
int n,s;
printf("Enter any limit number ");
scanf("%d",&n);
s=prod(n); /* function calling */
printf("the prod of the first %d numbers is %d \n",n,s);
return(0);
}
/* function definition */
int prod(int n)
{
if (n==0)
return(1);
else
return(n*prod(n-1));
}
Example:4
C program to calculate and print table of a number using recusion?

#include<stdio.h>
void table(int,int); /* function declaration */
int main()
{
int n,i=1;
printf("Enter any number ");
scanf("%d",&n);
table(n,i); /* function calling */
return(0);
}
/* function definition */
void table(int n,int i)
{
if (i>10)
return;
else
{
//printf("%d\n",i*n);
printf("%d * %d = %d\n",n,i,n*i);
table(n,i+1);
}
}
Example:5
C program to print Fibonacci series up to a limit using recursion?

#include<stdio.h>
#include<conio.h>
void fibo(int,int); /* function declaration */
void main()
{
int n;
clrscr();
printf("Enter any limit ");
scanf("%d",&n);
/* if we want 0 1 should also come at start/ printf("0 1 "); / else not / fibo(n,1); / function calling */
getch();
}
/* function definition */
void fibo(int n,int f3)
{
static int f1=0,f2=1;
f3=f1+f2;
if(f3<=n)
{
printf("%d ",f3);
f1=f2;
f2=f3;
fibo(n,f3);
}
else
return;
}




