Recursion in C – free C programming tutorial

In this tutorial you will be familiarized with the recursion technique available for C programming language along with example of a C program to determine factorial of the number entered by user or given number..

Recursion:

Recursion in C language is defined as a technique in which a function called itself i.e. it is a repetitive process.

In some ways it is similar to the looping staments i.e. iterative statements.

A simple example of is given below :

factorial()
{
     statements
     factorial();
}
int main()
{
    factorial();
}

Factorial:

Factorial is defined as the product of an integer and all the integers below it.

factorial of 0 i.e. 0! = 1
Also the factorial of 1 i.e. 1! = 1

Factorial of a number ‘n’ is given as :
n! = 1*2*3*4*5*…* (n-1)

For example :
factorial five  i.e. 5! is equal to 120.
6!  = 6*5*4*3*2*1
= 720

Various ways to determine factorial are explained below :

Normal way to determine factorial is by using iteration statement i.e. for loop statement :

Sample code for determining factorial of entered number by user by using iteration statement – for loop statement  is written below:

#include <stdio.h>
int main()
 {
   int i, num , fact = 1;

   printf("Enter a number to calculate its factorial... \n");
   scanf("%d", &num);

   for (c = 1; c <= num; c++)
     {
       fact = fact * c;
     }

  printf("Factorial of %d = %d\n", num, fact);
  return 0;
}

Factorial is obtained simply by incrementing number and multiply it by factorial i.e. fact = fact * c.
mathematically 1*2*3*4*5*6 = 720

When the above code in C language is compiled and executed, the result given below is obtained.

OUTPUT:

Enter a number to calculate its factorial... 6
Factorial of 6 = 720

Factorial of a Number Using Recursion

Sample code for determining factorial of entered number by user by using recursion-technique is written below:

#include <stdio.h>
long int multiplyNumbers(int n);

int main()
{
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %ld", n, multiplyNumbers(n));
    return 0;
}
long int multiplyNumbers(int n)
{
    if (n >= 1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}

multiplyNumbers(int n) called itself repetitively form 6 until 1 is reached.
mathematically 6*5*4*3*2*1 = 720

When the above code in C language is compiled and executed, the result given below is obtained.

OUTPUT:

Enter a positive integer: 6
Factorial of 6 = 720
This is all about the recursion technique available for C programming  language along with example of a C program to determine factorial of the number entered by user or given number.
If you have any query please comment below.

Leave a Comment

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