Identifying the Base Case

Base Case

Identifying the Base Case

🙋 Need help? Ask an expert now!

Let's examine the function of a "base case". It returns a value and does not make any more recurring calls. The values for which the base case stops recurring calls are particular specific inputs. For base cases that are factorial-based, the base case happens when the parameter becomes equal to one. Take a look at the code below.

IdentifyingBaseCaseExample.java
package exlcode;

public class IdentifyingBaseCaseExample {

  public static int exampleVariableOne = 10;

  public static void main(String[] args) {
    System.out.println(factorial(3));
  }

  public static int factorial(int parameterOne) {
    int result;
    // base case
    // returns 1 when exampleVariableTwo = 1
    if (parameterOne == 1) {
      return 1;
    }
    // calls factorial with exampleVariableTwo - 1
    // and multiplies the current value of exampleVariableTwo
    // with the result of the factorial(exampleVariableTwo - 1)
    result = factorial(parameterOne - 1) * parameterOne;
    return result;
  }
}

Did you receive an output of six? The program is working as intended because three factorial is equal to six. If we take a look at what happens in the method step by step, we see that the if statement is the "base case".

  1. factorial(3)
  2. result = factorial(2) * 3;
  3. factorial(2)
  4. result = factorial(1) * 2;
  5. factorial(1)
  6. return 1;
  7. result = 1 * 2;
  8. return result; (result is 2)
  9. result = 2 * 3;
  10. return result; (result is 6)

Line four and seven, two and nine are referring to the same line of code. This is because the return statement can't be called until factorial(2) and factorial(1) returned a number.

Edit Me on GitHub!

Application Question

Consider the following code segment:

private int calculate (int paramOne){
  if (paramOne <= 1){
    return 1;
  } else {
    return paramOne * calculate(paramOne - 2);
  }
}

Which of the following is printed as a result of the call calculate(5)?