Lesson 21 of 34

Recursion: Methods That Call Themselves

10 min 35 XP

A recursive method calls itself with a smaller input. It needs a base case (where it stops) and a recursive case (a call on a smaller problem). Without a base case you get a StackOverflowError.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

sumTo(3) = 3 + sumTo(2) = 3 + 2 + sumTo(1) = 3 + 2 + 1 + sumTo(0) = 6. Tracing it on paper like this makes recursion click.

Challenge

+35 XP

Write a recursive method static int power(int base, int exp) without Math.pow. In main(), read base and exp and print the result. Input: 2 10 → Output: 1024

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.