Codiqo

Learn Java · lesson 51 of 61 · about 9 minutes

Recursion on Arrays and Strings

Handle one item, then let a recursive call handle the rest.

What you'll learn

  • Recurse over an array with an index
  • Recurse over a string
  • Choose the right stopping point

Counting the tills

Before the doors lock, the manager counts the tills. The amount in each till is typed in cents on one line, like 4000 1250 875, and the desk sums them up: 3 tills: $61.25 in all, biggest $40.00. Two recursive methods do the work on the array of tills: tillTotal adds till i to the total of the tills after it, and biggestTill keeps the bigger of till i and the biggest of the tills after it. Both pass the array and an index that moves one place on each call.

An index instead of a copy

Copying an array on every call would be slow, so recursive methods pass the array and an index that says where to start.

The total from index i onwards is a[i] plus the total from i + 1. When i reaches a.length, there's nothing left, so the total is 0.

Adding up an array

public class Main {
    static int total(int[] a, int i) {
        if (i == a.length) return 0;
        return a[i] + total(a, i + 1);
    }

    public static void main(String[] args) {
        int[] nums = {4, 1, 5, 2};
        System.out.println(total(nums, 0));
    }
}

Output

12

Strings work the same way

s.charAt(0) is the first character and s.substring(1) is the rest. To reverse a string, reverse the rest first, then add the first character on the end. The base case is the empty string.

Reversing text

public class Main {
    static String reverse(String s) {
        if (s.isEmpty()) return "";
        return reverse(s.substring(1)) + s.charAt(0);
    }

    public static void main(String[] args) {
        System.out.println(reverse("phoebe"));
    }
}

Output

ebeohp

A different base case for the biggest

Not every question has an answer for no items at all. The total of no tills is 0, but there's no biggest among none. So biggestTill stops at the last till, i == tills.length - 1, which is the biggest of itself, and the desk only calls it when at least one till was typed.

Tip

For flat arrays a loop is usually simpler. Recursion shines when a problem naturally splits into smaller copies of itself, like spreading across a grid in this unit's project.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.