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.
public static void printDigits(int num)
num as input (0 ≤ num ≤ 10000).num in a consecutive order.printDigits(1234);
// Output: 1 2 3 4
printDigits(987654321);
// Output: 9 8 7 6 5 4 3 2 1
printDigits(0);
// Output: 0
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);
}
num becomes 0. In this case, we simply print the digit 0 and return.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.num.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.