Recursive functions are commonly used to implement mathematical computations that
can be defined in terms of smaller subproblems. Examples include factorials,
Fibonacci numbers, and power calculations.
In such functions, the mathematical definition of the problem naturally leads to
a recursive solution. Each function call computes a partial result and relies on
the result of a smaller input value. Recursive mathematical functions clearly
demonstrate the importance of base cases and proper termination conditions.
can be defined in terms of smaller subproblems. Examples include factorials,
Fibonacci numbers, and power calculations.
In such functions, the mathematical definition of the problem naturally leads to
a recursive solution. Each function call computes a partial result and relies on
the result of a smaller input value. Recursive mathematical functions clearly
demonstrate the importance of base cases and proper termination conditions.
EXAMPLE:
//Factorial
#include <stdio.h>
int factorial(int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
printf("Factorial of 5 is: %d", factorial(5));
return 0;
}
EXAMPLE:
//Fibonacci
#include <stdio.h>
int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
int main() {
printf("Fibonacci at position 5 is: %d", fib(5));
return 0;
}