Part 4, C Recursion
Part 4, C Recursion
1
Recursions
C is a powerful programming language having capabilities like an iteration of
a set of statements 'n' number of times. The same concepts can be done using
functions also. In this part, you will be learning about recursion concept and
how it can be used in the C program.
2
What is Recursion
A recursive function is a function that calls itself again and again, and the process continues till a
specific condition is reached.
void recursivefunc(void)
{
//some statements
recursivefunc(); //function calls itself
//further statements
}
int main(void)
{
recursivefunc();
return 0;
}
3
C program allows us to define and use recursive functions, but when we
implement this recursion concept, we must be cautious in defining an exit or
terminating condition from this recursive function, or else it will continue to
an infinite loop, so make sure that the condition is set within your program.
Let’s take some examples.
Factorial Program in C using Recursion
Example:
#include<stdio.h>
#include<conio.h>
int fact(int f)
{
if (f == 0 || f == 1)
{
return 1;
}
getch();
return 0;
}
Output:
The factorial of 12 is 479001600
6
Fibonacci program in C using recursion:
7
Example:
#include<stdio.h>
#include<conio.h>
int fibo(int g)
{
if (g == 0)
{
return 0;
}
if (g == 1)
{
return 1;
}
getch();
return 0;
}
Output:
Calculated Fibonacci
0 1 1 2 3 5 8 13 21 34
9