KotlinCS 124 LogoJava
PrevIndexNext
Kotlin
Java
  • Recursion : 11/04/2026

  • Working With Agents: Say What You Saw : 11/03/2026

  • Working With Agents: Validate What It Built : 11/02/2026

  • Lists Review and Performance : 10/30/2026

  • Linked Lists : 10/29/2026

  • Algorithms and Lists : 10/28/2026

  • Working With Agents: Correct It, Out Loud, Early : 10/27/2026

  • Working With Agents: Discuss Ideas, Not Implementations : 10/26/2026

  • Lambda Expressions : 10/23/2026

  • Anonymous Classes : 10/22/2026

  • Practice with Interfaces : 10/21/2026

  • Implementing Interfaces : 10/20/2026

  • Using Interfaces : 10/19/2026

  • Working with Exceptions : 10/16/2026

  • Throwing Exceptions : 10/15/2026

  • Catching Exceptions : 10/14/2026

  • References and Polymorphism : 10/13/2026

  • References : 10/12/2026

  • Data Modeling 2 : 10/09/2026

  • Equality and Object Copying : 10/08/2026

  • Polymorphism : 10/07/2026

  • Inheritance : 10/06/2026

  • Data Modeling 1 : 10/05/2026

  • Static : 10/02/2026

  • Encapsulation : 10/01/2026

  • Constructors : 09/30/2026

  • Objects, Continued : 09/29/2026

  • Introduction to Objects : 09/28/2026

  • Testing and Compilation : 09/25/2026

  • Practice with Collections : 09/24/2026

  • Maps and Sets : 09/23/2026

  • Lists and Type Parameters : 09/22/2026

  • Imports and Libraries : 09/21/2026

  • Multidimensional Arrays : 09/18/2026

  • Practice with Strings : 09/17/2026

  • null : 09/16/2026

  • Algorithms and Strings : 09/15/2026

  • Strings : 09/14/2026

  • Functions and Algorithms : 09/11/2026

  • Practice with Functions : 09/10/2026

  • More About Functions : 09/09/2026

  • Errors and Debugging : 09/08/2026

  • Functions : 09/04/2026

  • Practice with Loops and Algorithms : 09/03/2026

  • Algorithms : 09/02/2026

  • Loops : 09/01/2026

  • Arrays : 08/31/2026

  • Compound Conditionals : 08/28/2026

  • Conditional Expressions and Statements : 08/27/2026

  • Operations on Variables : 08/26/2026

  • Variables and Types : 08/25/2026

  • Welcome to CS 124 : 08/24/2026

Recursion

int countLetter(String string, char character) {
if (string == null) {
throw new IllegalArgumentException("String must not be null");
}
if (string.length() == 0) {
return 0;
}
if (string.charAt(0) == character) {
return 1 + countLetter(string.substring(1), character);
} else {
return 0 + countLetter(string.substring(1), character);
}
}
System.out.println(countLetter("you are not alone", 'o'));
System.out.println(countLetter("you are not alone", 'e'));

This lesson introduces a new problem solving strategy called recursion. Recursion represents an exciting new addition to our algorithm toolbox. It can be hard to wrap your head around at first. But we’ll go slow and, as always, use lots of examples. What are we waiting for?

What is Recursion?
What is Recursion?

So far we’ve looked exclusively at iterative algorithms that solve a problem by repeating a series of steps. The implementations of iterative algorithms are characterized by the use of looping constructs such as for and while.

Recursive algorithms work differently. They solve problems by breaking them down into smaller yet similar pieces, and the reassembling the solutions to the smaller problems into a solution to the larger problem. This will make more sense once we look at some examples!

But let’s start by examining both the general definition of recursion and how recursion is used in computer science.

Iteration v. Recursion
Iteration v. Recursion

Learning to think recursively takes time and practice. You’ll get both!

But let’s start by comparing and contrasting an iterative and recursive solution to the same problem. That will both help us start to learn to think recursively, and identify the differences between the two approaches.

Is A Palindrome: Iterative
Is A Palindrome: Iterative

Let’s write an algorithm to determine if a String is a palindrome, that is, whether it reads the same forwards and backwards. First, let’s design an iterative algorithm:

// Iterative Palindrome

Is A Palindrome: Recursive
Is A Palindrome: Recursive

Next, let’s try and approach the problem recursively.

What does that mean? A recursive solution tries to make the problem smaller in each step until it is trivial to solve. Let’s think about how to apply that to palindrome detection.

// Recursive Palindrome

Compare and Contrast
Compare and Contrast

To wrap up, let’s put the two approaches side by side and discuss the differences.

// Iterative Palindrome v. Recursive Palindrome

Recursive Strategies
Recursive Strategies

A recursive implementation contains a function that calls itself. At first, this may seem really weird. But the trick is not to not let that throw you, and to just consider what happens.

Successful recursive algorithms must do three things correctly:

  1. Make the problem smaller. If you don’t do this, the problem never gets small enough to solve!
  2. Solve the smallest problem. This is known as the base case.
  3. Combine the results properly. This is required to arrive at a correct solution.

Let’s examine another recursive implementation. We’ll identify the three requirements enumerated above, and trace its execution.

int countLetter(String string, char character) {
if (string == null) {
throw new IllegalArgumentException("String must not be null");
}
if (string.length() == 0) {
return 0;
}
if (string.charAt(0) == character) {
return 1 + countLetter(string.substring(1), character);
} else {
return 0 + countLetter(string.substring(1), character);
}
}

Factorial
Factorial

The next homework problem has you complete a recursive implementation of factorial. For reference, here is the iterative implementation that matches the homework problem:

public static long factorial(long input) {
// factorial gets big really quickly
if (input < 0 || input > 20) {
throw new IllegalArgumentException();
}
long result = 1;
for (long multiplier = 2; multiplier <= input; multiplier++) {
result *= multiplier;
}
return result;
}
assert factorial(0) == 1;
assert factorial(2) == 2;
assert factorial(4) == 24;

To complete the recursive implementation, consider the following questions:

  1. What is the smallest problem, or the base case? (You know that the factorial of 0 is 1).
  2. How do you make the problem smaller and combine the results? (You know that the factorial of n is n * n - 1).

Practice: Solve Recursive Factorial

Created By: Geoffrey Challen
/ Version: 2020.11.0

Create a public class Factorial that provides a single static method factorial. factorial accepts a single long and returns its factorial as a long. You can reject negative arguments and ones greater than 20 by throwing an IllegalArgumentException.

You should submit a recursive solution. The factorial of 0 is 1, and this represents the base case. The factorial of n is n * the factorial of n - 1, and this represents the recursive step.

Code Quality: Avoiding Inefficient Programs
Code Quality: Avoiding Inefficient Programs

As a reminder: In CS 124, in addition to teaching you how to write correct code, we also want to teach you how to write good code: Code that’s beautiful and elegant and that you and those you work with will be proud of.

There are multiple aspects of code quality that we’ll be introducing throughout the semester. Previously we talked about ensuring beautiful code formatting using checkstyle, removing unnecessary debugging output, eliminating dead code, avoiding overly-long code, and reducing code complexity. checkstyle rules are now enforced on homework and quizzes, and starting today, there will be a one-point deduction for correct submissions that produce unnecessary debugging output, contain dead code, are much longer than the reference solution, or are unnecessarily complex.

The next aspect of code quality we’ll discuss is execution efficiency, which we measure by the number of lines that your submission executes. CS 124 is not a course on code optimization or one that places a significant premium on execution efficiency. However, we still do want you to avoid submitting code that is way more inefficient than the reference solution.

Let’s see an example of how that works using a familiar practice problem:

int whoWon(int first, int second, boolean playedFirst) {
int unneeded = first;
for (int i = 0; i < 16; i++) {
unneeded = first;
}
if (first > second) {
return 1;
} else if (second > first) {
return 2;
} else {
if (playedFirst) {
return 2;
} else {
return 1;
}
}
}

We’ll be warning you about significantly inefficient programs starting today, and in a few weeks you’ll lose one point on the graded homework if you don’t reduce the execution count appropriately.

Homework: Solve Recursive Range Sum

Created By: Geoffrey Challen
/ Version: 2021.10.0

Create a class RangeSum with a public static method sum that accepts a single int value and returns the sum of all the integers in the range 1..value as an int. So, for example, given the input 10 you should return 55: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10. You can reject arguments less than or equal to 0 and ones greater than 128 by throwing an IllegalArgumentException.

You should submit a recursive solution. The range sum of 1 is 1, and this represents the base case. The range sum of n is n + the range sum of n - 1, and this represents the recursive step.

More Practice

Need more practice? Head over to the practice page.