C Language Video

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484

Recursive Functions

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. The C programming language supports recursion, i.e., a function to call itself.

 

Format of Recursion

 

void recursion() {

   recursion(); /* function calls itself */

}

 

int main() {

   recursion();

}

 


 

Example-1

calculates the factorial of a given number using a recursive function.

 

#include <stdio.h>

 

int factorial(int i) {

 

   if(i <= 1) {

      return 1;

   }

   return i * factorial(i - 1);

}

 

int  main() {

   int n = 4;

   printf("Factorial of %d is %d\n", n, factorial(n));

   return 0;

}


 

Example-2

Generates the Fibonacci series for a given number using a recursive function.

#include <stdio.h>

 

int fibonacci(int i) {

   if(i == 0) {      return 0;   }

   if(i == 1) {       return 1;   }

   return fibonacci(i-1) + fibonacci(i-2);

}

 

int  main() {

   int i;

   for (i = 0; i < 10; i++) {

      printf("%d\t\n", fibonacci(i));

   }

       

   return 0;

}

 

C Language Video

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484