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

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


Recursion in C


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 Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.