C Recursive Functions

A recursive function in C is a function that calls itself in order to solve a problem. It breaks a problem into smaller versions of the same problem until it reaches a simple case, known as the base case, which stops the recursion.

A recursive function generally has two parts

1. Base case: This defines the stopping condition for the recursion.

2. Recursive case: This part breaks down the problem into smaller sub-problems and calls the function itself.

General Structure of Recursive Function:


return_type function_name(parameters) {
    if (base_case_condition) {
        // Return result (or handle the simplest case)
    } else {
        // Recursive case (call the function itself)
        return function_name(smaller_sub_problem);
    }
}

Example: Factorial Program


#include <stdio.h>

int factorial(int n) {
    if (n == 0) {
        return 1;  // Base case
    } else {
        return n * factorial(n - 1);  // Recursive case
    }
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    
    printf("Factorial of %d is %d\n", num, factorial(num));
    return 0;
}

Output:

Enter a number: 5
Factorial of 5 is 120

Explanation:

  1. The function factorial checks if n is 0. If true, it returns 1 (base case).
  2. Otherwise, it multiplies n by the factorial of n – 1, recursively calling the factorial function until the base case is reached.

C Recursive Functions – Interview Questions

Q 1: What is a recursive function?

Ans: A function that calls itself to solve a problem.

Q 2: What is a base condition in recursion?

Ans: A condition that stops the recursive calls.

Q 3: Why is a base condition important?

Ans: To prevent infinite recursion.

Q 4: What are the disadvantages of recursion?

Ans: Higher memory usage and slower execution compared to loops.

Q 5: Where is recursion commonly used?

Ans: In problems like factorial, Fibonacci, and tree traversal.

C Recursive Functions – Objective Questions (MCQs)

Q1. What is recursion in C?






Q2. What is essential for a recursive function to avoid infinite recursion?






Q3. Which of the following is an example of recursion?






Q4. Which of the following problems is commonly solved using recursion?






Q5. What happens if a recursive function does not have a base case?






Related C Recursive Functions Topics