Recursion in C

 Recursion


Recursion is a programming technique where a function calls itself to solve a problem. It is particularly useful for solving problems that can be divided into smaller subproblems. However, it's important to handle base cases to prevent infinite recursion.



#include <stdio.h>


int factorial(int n) {

    if (n == 0) {

        return 1; // Base case: factorial of 0 is 1

    } else {

        return n * factorial(n - 1); // Recursive call

    }

}


int main() {

    int n = 5;

    int result = factorial(n);

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


    return 0;

}

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...