C - Recursion

Recursion is a programming technique in which a function calls itself to solve a problem. It's a way to break down a complex problem into smaller, more manageable subproblems. Recursive functions typically have two parts: a base case and a recursive case.

Base Case:

The base case defines the simplest scenario where the function does not call itself but returns a known result. It serves as the exit condition for the recursion, preventing infinite loops.

Recursive Case:

In the recursive case, the function calls itself with a modified input to solve a smaller instance of the problem. The function continues to call itself until it reaches the base case.

Recursion is useful in situations where a problem can be divided into smaller, similar subproblems. Common examples include solving mathematical sequences (e.g., Fibonacci series), traversing tree-like data structures (e.g., binary trees), and exploring all possible combinations (e.g., permutation generation).

Example: Fibonacci Sequence

#include <stdio.h>

// Recursive function to calculate the nth Fibonacci number
int fibonacci(int n) {
    // Base case: If n is 0 or 1, return n
    if (n <= 1) {
        return n;
    } else {
        // Recursive case: Calculate the sum of the previous two Fibonacci numbers
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

int main() {
    int n;

    printf("Enter the value of n: ");
    scanf("%d", &n);

    if (n < 0) {
        printf("Fibonacci sequence is not defined for negative numbers.\n");
    } else {
        printf("Fibonacci sequence up to the %dth term:\n", n);
        for (int i = 0; i <= n; i++) {
            printf("%d ", fibonacci(i));
        }
        printf("\n");
    }

    return 0;
}
    

Explanation of the Fibonacci recursion example:

  1. The fibonacci function takes an integer n as input and calculates the nth Fibonacci number.
  2. In the base case (when n is 0 or 1), the function returns n because the Fibonacci sequence starts with 0 and 1.
  3. In the recursive case, the function calls itself twice with n - 1 and n - 2 to calculate the previous two Fibonacci numbers and then adds them together to get the current Fibonacci number.
  4. The main function takes user input for n, checks for a negative value, and then prints the Fibonacci sequence up to the nth term.

When you run the program, it will calculate and display the Fibonacci sequence up to the specified term, demonstrating the concept of recursion.

Example 1: n = 5

Enter the value of n: 5
Fibonacci sequence up to the 5th term:
0 1 1 2 3 5
    
Example 2: n = 0

Enter the value of n: 0
Fibonacci sequence up to the 0th term:
0
    
Example 3: n = -3

Enter the value of n: -3
Fibonacci sequence is not defined for negative numbers.
    

The output of the program depends on the value of n, and it will display the Fibonacci sequence up to the specified term or show an error message for negative values of n.