Recursion in C

In the last tutorial I told you about the function calls i.e. call by value and call by reference. Today I will tell about the last advance feature of function i.e. recursion in C. So lets straight away starts it with a simple example.

Recursion in C

#include<stdio.h>

void crashp();

int main()
{
	crashp();

	return 0;
}

void crashp()
{
	crashp();	//calling funtion itself
}

This is the simplest example of a recursive function. A function is said to be recursive function when it calls itself. In the above you can see the function crashp() is calling itself again and again.

What will be the output of the above program?
As you can see crashp() function is calling itself again and again. So this program will create an infinite loop and it will never end. In this case press Ctrl+PauseBreak button to stop the execution.

Note: It is quite difficult to show the working of recursive function. Therefore, I recommend you to read the basic concepts of functions first before proceeding further. Working of recursive function totally depends on the basic concepts.

Lets take another example of a recursive function to calculate factorial of a number.

Program for factorial using recursion in C

#include<stdio.h>

int factorial(int x)
{
   if(x<=1)
   {
      return 1;
   }
   return (x * factorial(x-1));
}

int main()
{
    int x=5;
    printf("Factorial of %d is %dn",x,factorial(x));
    return 0;
}

Output

Recursion in C

Explanation

1. Program execution starts from the main() function. I have already assigned integer variable x with value 5.

2. After that I have written the printf() function.

3. Inside printf() function I have called factorial() function to calculate the factorial value.

4. Now the function factorial() will call itself until value of x makes this condition true (x<=1)

5. Consider the return statement of factorial() function carefully i.e. return x * factorial(x-1);

It will solve the answer in this way 5*4*3*2*1=120

Recursion in C
Image Source

Its quite tricky to understand the execution of a recursive function. But go through the above tutorial at least 2-3 times for better understanding. So this brings us to the end of functions. Now in the next tutorial I will tell you about the extended data types.

Leave a Comment

Your email address will not be published. Required fields are marked *