C Program codes using recursion


Recursive functions are functions that calls itself. This calling maybe direct or indirect. This process is called recursion. Using recursion we can solve certain problems very easily. The problems we have done using recursion are:
  • Sum of n natural numbers
  • Finding the nth element in Fibonacci series.
  • Factorial of a number.

SUM OF n NATURAL NUMBERS

#include<stdio.h>
int sumn(int n)
{
if(n == 0)
{
return 0;
}
else if(n == 1)
{
return 1;
}
else
{
return n + sumn(n-1);
}
}
int main()
{
int n,ans;
printf("Enter the nth value: ");
scanf("%d",&n);
ans = sumn(n);
printf("The sum of first %d natural numbers is %d",n,ans);
getch();
return(0);
}
view raw gistfile1.txt hosted with ❤ by GitHub


FINDING THE nTH ELEMENT IN THE FIBONACCI SERIES

#include<stdio.h>
int fibo(int n)
{
if(n == 0)
{
return 0;
}
else if(n == 1)
{
return 0;
}
else if(n == 2)
{
return 1;
}
else if(n == 3)
{
return 1;
}
else
{
return fibo(n-1) + fibo(n-2);
}
}
int main()
{
int n,ans;
printf("Enter the value of n: ");
scanf("%d",&n);
ans = fibo(n);
printf("The %d th element in the fibonacci series is %d",n,ans);
getch();
return(0);
}
view raw gistfile1.txt hosted with ❤ by GitHub

FACTORIAL OF A NUMBER


#include<stdio.h>
int facto(int n)
{
if(n == 0)
{
return 1;
}
else if(n == 1)
{
return 1;
}
else
{
return n * facto(n-1);
}
}
int main()
{
int n,ans;
printf("Enter the number to find factorial: ");
scanf("%d",&n);
ans = facto(n);
printf("%d ! = %d",n,ans);
getch();
return(0);
}
view raw gistfile1.txt hosted with ❤ by GitHub

Comments