Mastering Recursive Functions in C: A Comprehensive Guide

Recursive Functions in C

Sometimes a function calls itself, such a function is called ‘Recursive function‘. For example if we want to find factorial value of 3. The factorial value of 3 is dependent on the factorial value of 2.

factorial(3) = 3 * factorial(2)
Here, factorial(2) = 2 * factorial(1)
Also, factorial(1) = 1 * factorial(0)

Now, if we know that the value of factorial(0) is 1, all the preceding statements will yield the result.

factorial(3) = 3 * factorial(2)
             = 3 * 2 * factorial(1)
             = 3 * 2 * 1 * factorial(0)
             = 3 * 2 * 1 * 1
             = 6

the formula is factorial(n)=n* factorial(n-1). If we imagine the factorial function, to calculate factorial(n), it should call itself to find the factorial(n-1). So, the factorial function looks something like this:

long int factorial(int n)
{
    long int result;
    if(n == 0)
    result = 1;
    else
        result=n*factorial(n-1);
    return result;
}

Scope of Variables:

When a variable is declared in a function,by default the scope of the variable becomes ‘block scope’. It means that variable will be available inside the function body (block) only. It will not be available outside the function, to other functions.

Example:void funct()
   {
      int x=1;
      x++;
   }

Here, the variable x value will not be available to other functions. It is available only inside that function. To make it available to other functions, we should return the variable value using return statement.The duration of the variable x is temporary. It means every time the function is called, the variable is recreated. Thus, previous value is deleted.

Creating our own header files:

First of all the functions should be typed and stored as a header file with .h extension. For example we can type all the functions: add(), sub(), mul(), divide() and save that code as ‘arithmetic.h’.

Once the header file is ready, it can be included and used in any other program. The include statement should be written as:

#include "arithmetic.h"

Here,the double quotes represent that, the header file is created by the user and it is not built in header file from c library. To use this header file, it should be available in the current directory where the program’s .exe file is located. If the file is located in another directory, then that directory path should be included in the double quotes.

Example: #include "C:\mydrive\arithmetic.h"
Naveed Tawargeri
 

Hi, I'm Naveed Tawargeri, and I'm the owner and creator of this blog. I'm a Software Developer with a passion for Programming.