Post

Created by @nathanedwards
 at November 2nd 2023, 11:11:27 am.

AP Computer Science Exam Question:

You are given a recursive method printDigits(int num) that takes an integer num as input and prints all the individual digits of num in a consecutive order. Write the recursive method printDigits to fulfill this requirement.

Method Signature

public static void printDigits(int num)

Input

  • The method takes an integer num as input (0 ≤ num ≤ 10000).

Output

  • The method prints all the individual digits of num in a consecutive order.

Example

printDigits(1234);
// Output: 1 2 3 4

printDigits(987654321);
// Output: 9 8 7 6 5 4 3 2 1

printDigits(0);
// Output: 0

Answer:

public static void printDigits(int num) {
    // Base case: When num becomes 0, return.
    if (num == 0) {
        System.out.print(num);
        return;
    }
  
    // Recursively divide num by 10 to get the quotient and remainder.
    int quotient = num / 10;
    int remainder = num % 10;
  
    // Recursive call on the quotient.
    printDigits(quotient);
  
    // Print the remainder.
    System.out.print(" " + remainder);
}

Step-by-step Explanation:

  1. The base case for the recursive method is when num becomes 0. In this case, we simply print the digit 0 and return.
  2. Inside the recursive method, we divide num by 10 to get the quotient and remainder. The quotient represents the remaining digits after removing the last digit, and the remainder represents the last digit.
  3. We make a recursive call on the quotient. This ensures that the method is applied to all the remaining digits recursively.
  4. Finally, we print the remainder, which represents the last digit of the original number num.
  5. With each recursive call, the method unwinds and prints the remaining digits in reverse order until num becomes 0, at which point the base case is triggered and the recursion stops.

This approach allows us to print all the individual digits of num recursively in a consecutive order.