Recursion in C

 Recursion in C


Recursion is a technique in which a function calls itself to solve a problem. It is useful for solving problems that can be divided into smaller subproblems. However, recursion should be used with caution to avoid infinite recursion and excessive memory usage.


#include <stdio.h>


int factorial(int n) {

    if (n == 0) {

        return 1;

    } else {

        return n * factorial(n - 1);

    }

}


int main() {

    int num = 5;

    int result = factorial(num);


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


    return 0;

}

In this example, the factorial function calculates the factorial of a number using recursion. The function calls itself with a smaller value until the base case is reached.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...