Recursive functions in C are a powerful programming tool that allows tasks to be broken down into smaller, manageable pieces. They work by having a function call itself to solve sub-problems, mimicking processes like tracing ancestry or cutting a pizza into smaller slices.
Recursion relies on two key elements:
For example, calculating the sum of natural numbers, finding a factorial, or generating a Fibonacci series are classic uses of recursion. Each problem is solved step-by-step until the base case is reached, making recursion a clean and elegant solution for many tasks.
Explore the examples of recursive functions in C to see this concept in action and understand how it simplifies complex problems!
Scenario: To trace your ancestry, you look at your parents, then their parents, and so on, until you reach the earliest known ancestor.
Cutting a Pizza
_______________________________
Sum of n natural numbers:
———————————
#include <stdio.h>
int sum(int n)
{
if(n==1)
return 1;
else
return n+sum(n-1);
}
int main()
{
int no=sum(5);
printf(“%d”,no);
}
#include <stdio.h>
int sum(int n)
{
if(n==1)
return 1;
else
return n*sum(n-1);
}
int main()
{
int no=sum(5);
printf(“%d”,no);
}
Fibonacci series:
#include <stdio.h>
int sum(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return sum(n-1)+sum(n-2);
}
int main()
{
int no=sum(5);
printf(“%d”,no);
}
Indian Institute of Embedded Systems – IIES