Recursion in C

For Complete YouTube Video: Click Here

In this class, we will Understand Recursion in C.

The concept of recursion is based on the process of the program, which we have discussed.

Understanding Recursion

Recursion means a function calling itself.

If a function is calling itself, then it is called a recursive function.

The recursive function calls will help us solve problems.

How the problems are solved is based on how a process works.

To understand the concept of recursion, we will use the factorial program as shown below.

In the above program, the seventh line of the fact function is calling itself.

The fact function is recursive. It is calling itself.

Let’s try to understand the recursive program execution by using the process of a program.

A new activation record will be created when the main function is called, as shown in the image below.

Recursion in C
Recursion in C Main Activation Record

Please assume that the user wants to find three factorial, and the value of i is scanned to three.

In the fourth line of the main, the fact(3) function call is made.

A new activation record for the fact(3) will be created, as shown in the image.

Recursion in C fact(3) Activation Record
Recursion in C fact(3) Activation Record

While executing fact(3) function at seventh line fact(n-1) which is fact(2) recursive function call is made.

While executing fact(2) function at seventh line fact(n-1) which is fact(1) recursive function call is made.

Now the value of n is equal to 1, and the function will be return one to the calling function, which is the fact(2).

Now n * 1 is returned to calling function fact(3), as shown below.

In this way, we can solve problems by using recursive function calls.

For better Understanding watch the video above.