REC - Recursion (Lesson)

APCompSci_LessonTopBanner.png

Recursion

Introduction

Recursion is a method that calls itself.

public void mystery (int n)
{

if (n > 1)
{
System.out.print(n);
mystery(n - 2);
}

else
{
System.out.print(n);
}
}
 

Notice in this mystery method, mystery is called again as part of the if statement. In order to call this method, we must call the method again.

All recursive methods have a base case. This is the condition that allows the recursion to end.

public void mystery(int n)
{

if (n > 1) //this is the line indicating the base case
{
System.out.print(n);
mystery(n-2); //this is the recursive call
}

else
{
System.out.print(n);
}
} 

In the mystery method, 1 is the base case since the method will stop calling itself when the parameter is 1 or less. If we did not have a base case, we would have an infinite recursive method.

Tracing a Recursive Method

To trace a recursive method, we create a stack where we start at the bottom and work our way up and then back down. For example, let’s try our mystery method when n = 10.

public void mystery(int n)
{

if (n > 1)
{
System.out.print(n);
mystery(n - 2);
}

else
{
System.out.print(n);
}
} 

 

mystery(0) = 0
mystery(2) = 2mystery(0)
mystery(4) = 4mystery(2)
mystery(6) = 6 mystery(4)
mystery(8) = 8 mystery (6)
Start here mystery (10) = 10 mystery(8) 

Once we reach the base, in our case mystery(0), we can start at the top and substitute our values back in:

mystery(0) = 0
mystery(2) = 2 mystery(0) = 2 0
mystery(4) = 4 mystery(2) = 4 2 0
mystery(6) = 6 mystery(4) = 6 4 2 0
mystery(8) = 8 mystery (6) = 8 6 4 2 0
mystery(10) = 10 mystery(8) = 10 8 6 4 2 0 

Therefore, mystery(10) prints 10 8 6 4 2 0.

BookIcon.png Click on "Runestone Academy" below to open the required reading that is listed.

Runestone Academy: AP CSA – Java Review Links to an external site.

  • READ: 12 – Recursion

BookIcon.png Click on "Introduction to Computer Science Using Java" below to open the required reading that is listed.

Introduction to Computer Science Using Java Links to an external site.

  • READ:
  • Chapter 90: Recursion
  • Chapter 91: Recursion in Java
  • Chapter 92: Examples of Recursion
  • Complete the quizzes for practice.

BookIcon.png READ 5 Steps to a 5:

  • Concept 10
  • Concept 11

Practice It

Practice-It! Practice

Practice Icon Go to the PracticeIt website Links to an external site..

Log into account.

Click on Start Practicing!

Go to the most recent edition.

Click on Chapter 12: Recursion

Complete Self-Check: 12.3 – 12.6, 12.13 – 12.15

CodingBat Practice

Practice Icon Go to the CodingBat website Links to an external site..

Log into your account

Make sure that you are on the Java tab (not Python).

Select Recursion - 1.

Complete some Recursion - 1 exercises for practice.

***You will not be required to write recursive methods on the AP Exam.***

APCompSci_LessonBottomBanner.pngIMAGES CREATED BY GAVS