11.8.1. Base Case PracticeΒΆ
A recursive method contains a call to itself. The recursion stops when a base case test is true and a value is returned.
10-7-1-1: Click on the line or lines that contain the test for the base caseWhen a base case test is true a value is returned and the recursion stops
public static int mystery(int n) { if (n == 0) { return 1; } else { return 2 * mystery (n - 1); } }
10-7-1-2: Click on the line or lines that contain the test for the base caseWhen a base case test is true a value is returned and the recursion stops
public static int bunnyEars(int bunnies) { if (bunnies == 0) { return 0; } else if (bunnies == 1) { return 2; } else { return 2 + bunnyEars(bunnies - 1); } }
10-7-1-3: Click on the line or lines that contain the test for the base caseWhen a base case test is true a value is returned and the recursion stops
public static void mystery (int x) { System.out.print(x % 10); if ((x / 10) != 0) { mystery(x / 10); } System.out.print(x % 10); }
10-7-1-4: Click on the line or lines that contain the test for the base caseWhen a base case test is true a value is returned and the recursion stops
public static int mystery(String str) { if (str.length() == 1) { return 0; } else { if (str.substring(0, 1).equals("y")) { return 1 + mystery (str.substring(1)); } else { return mystery(str.substring(1)); } } }
You have attempted of activities on this page