C – Recursion

Taylor Emma
2 Min Read
Disclosure: This website may contain affiliate links, which means I may earn a commission if you click on the link and make a purchase. I only recommend products or services that I personally use and believe will add value to my readers. Your support is appreciated!

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.

void recursion(){

recursion();/* function calls itself */

}

int main(){

recursion();

}

The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

Number Factorial

The following example calculates the factorial of a given number using a recursive function −

#include<stdio.h>

int factorial(unsignedint i){

if(i <=1){

return1;

}

return i * factorial(i -1);

}

int  main(){

int i =15;

printf(“Factorial of %d is %d\n”, i, factorial(i));

return0;

}

When the above code is compiled and executed, it produces the following result −

Factorial of 15 is 2004310016

Fibonacci Series

The following example generates the Fibonacci series for a given number using a recursive function −

#include<stdio.h>

int fibonacci(int i){

if(i ==0){

return0;

}

if(i ==1){

return1;

}

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

}

int  main(){

int i;

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

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

}

return0;

}

When the above code is compiled and executed, it produces the following result −

0                  1                  1                  2                  3                  5                  8                  13               21               34

Share This Article
A senior editor for The Mars that left the company to join the team of SenseCentral as a news editor and content creator. An artist by nature who enjoys video games, guitars, action figures, cooking, painting, drawing and good music.
Leave a review