Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2. Recursion

Recursive thinking, the call stack, forward and backward phases, factorial, fast exponentiation, Fibonacci and the Towers of Hanoi, and how to solve recurrences. Problem solving: array maximum, palindromes, recursive binary search, counting, and generating all binary strings.

Slides

Present full screen Download the PDF

Click or tap the slide to move forward, its left edge to go back; the arrow keys work too.

Recursion exercises

Exercise 1: Searching for an element in an array

Write a recursive function that searches for an element in an array. The function should return the index of the element if it is found, and -1 otherwise.

Solution:

int search(int[] arr, int x) {
    return search(arr, 0, x);
}
int search(int[] arr, int i, int x) {
    if (i == arr.length) {
        return -1;
    }
    if (arr[i] == x) {
        return i;
    }
    return search(arr, i + 1, x);
}

Exercise 2: Compute the exponentiation of a number

Write a recursive function that computes the exponentiation of a number. The function should take two integers,

xx

and

nn

, and return

xnx^n

.

Solution:

int power(int x, int n) {
    if (n == 0) {
        return 1;
    }
    return x * power(x, n - 1);
}

Exercise 3: Computing the number of occurrences of a character in a string

Write a recursive function that computes the number of occurrences of a character in a string. The function should take a string and a character, and return the number of occurrences of the character in the string.

Solution:

int count(String s, char c) {
    return count(s, c, 0);
}
int count(String s, char c, int i) {
    if (i == s.length()) {
        return 0;
    }
    return (s.charAt(i) == c ? 1 : 0) + count(s, c, i + 1);
}