C Recursion

Recursion is when a function calls itself. Every recursive function needs a base case, which stops the calls. Without it the function calls itself forever, and the program crashes.

Factorial

Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120. We can say n! = n x (n-1)! and 0! = 1.

#include <stdio.h>

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

int main(void) {
    printf("5! = %d\n", factorial(5));
    return 0;
}

Output:

Output of the above program is

5! = 120

The calls go like this: factorial(5) waits for factorial(4), which waits for factorial(3), and so on until factorial(0) returns 1. Then the answers come back in reverse order.

Fibonacci series

#include <stdio.h>

int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}

int main(void) {
    for (int i = 0; i < 8; i++) {
        printf("%d ", fib(i));
    }
    printf("\n");
    return 0;
}

Output:

Output of the above program is

0 1 1 2 3 5 8 13

Sum of digits

#include <stdio.h>

int sumDigits(int n) {
    if (n == 0) return 0;
    return n % 10 + sumDigits(n / 10);
}

int main(void) {
    printf("%d\n", sumDigits(1234));
    return 0;
}

Output:

Output of the above program is

10

Recursion vs loop

  • Recursion code is short and clean for problems like trees, but it uses more memory (stack).
  • A loop is faster and safe for simple counting.
  • The simple Fibonacci above repeats the same work many times, so it is slow for big numbers.
Note: Always check that each call comes nearer to the base case. If not, you get a stack overflow.

Next: C Scope and Storage Classes.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.