13.1 Recursion conceptually

Recursion, Conceptually

Recursion is a problem that calls itself, directly or indirectly. Think of it like looking for a key in a box, finding another box, looking for the key in more smaller boxes until you find the key. This will make more sense once working through an example

Recursion has a base case and a recursive case. The base case is what we use when we don’t want the function to call itself. The recursive case is what we use when we want the function to call itself.

public static int factorial(int x)
			if (x == 1) //Base case
						return 1;
			else //Recursive Case
						return x * factorial(x-1);

This example follows this flowchart:

Let’s take x = 9.


This gives us 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 = 362880

The function calls itself to get a value to use, and does this until a base condition is met. This allows the initial function to finally run.

Next Section


Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.