C is a powerful programming language having capabilities like an iteration of a set of statements 'n' number of times. The same concepts can be done using functions also. In this tutorial, you will learn about the concept of recursion and how it can be used in C programs.



What is Recursion

Recursion can be defined as the technique of repeating or doing an activity, which calls itself repeatedly, and the process continues until a specific condition reaches. In the programming world, when your program lets you call that specific function from inside that function, then this concept of calling the function from itself can be termed recursion. The function that makes this possible is called the recursive function. Here's an example of how recursion works in a program:

Example:

void rec_prog(void) {
    rec_prog(); //function calls itself
}

int main(void) {
    rec_prog();
    return 0;
}

C program allows you to do the such calling of function within another function, i.e., recursion. But when you implement this recursion concept, you have to be cautious in defining an exit or terminating condition from this recursive function, or else it will continue to an infinite loop, so make sure that the condition is set within your program.

Factorial Program in C Using Recursion

Example:

#include<stdio.h>
#include<conio.h>

int fact(int f) {
    if (f==0 || f==1) {
        printf("Calculated Factorial");
        return 1;
    }
    return f * fact(f - 1);
}

int main(void) {
    int f = 12;
    printf("The factorial of %d is %d \n", f, fact(f));
    getch();
    return 0;
}

Output:

Calculated Factorial
The factorial of 12 is 479001600

Fibonacci Program in C Using Recursion

Example:

#include<stdio.h>
#include<conio.h>

int fibo(int g) {
    if (g == 0) {
        return 0;
    }

    if (g == 1) {
        return 1;
    }
    return fibo(g - 1) + fibo(g - 2);
}

int main(void) {
    int g;
    printf("Calculated Fibonacci\n");
    for (g = 0; g < 10; g++) {
        printf("%d \t ", fibo(g));
    }
    getch();
    return 0;
}

Output:

Calculated Fibonacci
0        1       1       2       3       5       8       13      21      34


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram