1. Recursion in C
Recursion is the mechanism of repeating objects in a similar manner to themselves. When a program
allows you to call a function inside the same function in programming languages, that function is called a
recursive call. Recursion can result in an intuitive, very simple, elegant code to follow. It may also
require the use of a very large amount of memory if the recursion is too long.
A function which itself calls is known as a recursive function. And, the strategy is called recursion.
Recursion can not be extended to all of the problem, but for the tasks that can be described in terms of
similar subtasks it is more useful. For example, recursion can be applied to problem sorting, searching,
and traversing.
C program helps you to do such function calling inside a specific function, i.e., a recursion. However
when introducing this definition of recursion, you must be careful to specify an exit or terminate
condition from this recursive function, or else it will lead to an infinite loop, so make sure the condition
is set within your program.
Example Syntax of Recursive Function in C
void rec_prog(void) {
rec_prog(); /* function calls itself */}
int main(void) {
rec_prog();
return 0;
}
Note: We need to describe correct exit condition in a recursive function to prevent indefinitely recursive
calling.
2. Example of recursive function in C programming : C program that uses iteration to identify the fact of
the first 6 natural numbers
#include <stdio.h>
#include<conio.h>
long int fact( int n )
{
if ( n <= 1 )
return 1;
else //here is recursive step
return ( n * fact (n-1) );
}
int main ()
{
int i;
for ( i = 1; i <=6; i++ )
printf("%d! = %dn",i, fact(i) );
return 0;
}
Output:
1! = 1
2! = 2
3! = 6
4! = 24
3. 5! = 120
6! = 720
Fibonacci series
#include<stdio.h>
#include<conio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}
Output:
Enter the number of elements: 5
4. 01123
Fibonacci series using Recursion in C programming
#include<stdio.h>
#include<conio.h>
void printFibonacci(int n){
static int n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2);//n-2 because 2 numbers are already printed
return 0;
}