C recursion
Created By: chatGPT
Recursion in C is a powerful tool that allows a function to call itself in order to solve a problem. A recursive function generally has two main components: a base case and a recursive case. The base case stops the recursion, while the recursive case continues to call the function until the base case is met.
#include <stdio.h>
int factorial(int n) {
// Base case
if (n == 0) {
return 1;
}
// Recursive case
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
In this example, the
factorial
function calculates the factorial of a number n
. When n
is 0, the function returns 1. For any other value, it calls itself with the value of n - 1
, multiplying it by n
until it reaches the base case.// Output:
// Factorial of 5 is 120
Recursion can also be used in other algorithms such as Fibonacci sequence calculation. Similar to the factorial example, this uses a base case to stop recursion and a recursive case to compute the Fibonacci number for
n
.int fibonacci(int n) {
// Base case
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
// Recursive case
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 6;
printf("Fibonacci of %d is %d\n", n, fibonacci(n));
return 0;
}
In this code snippet, the
fibonacci
function works by summing the two previous Fibonacci numbers. For example, fibonacci(6)
ultimately calls fibonacci(5)
and fibonacci(4)
, continuing until it evaluates base cases.// Output:
// Fibonacci of 6 is 8
Important Note: While recursion can simplify code, it may lead to performance issues, especially with deep recursion, due to potential stack overflow. Iterative solutions might be more effective in such cases. Always consider the size of the input when using recursion.
// Be cautious of deep recursion-based on input size