Reputation: 37
How would I use recursion to print the first parameter in the number base specified by the second parameter in the printConvertedNumber
method
import java.util.Scanner;
class NumberBaseConversion
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number,
base;
do
{
System.out.print("Enter a positive base 10 number: ");
number = input.nextInt();
} while (number <= 0);
do
{
System.out.print("Enter a base (2, 4, or 8): ");
base = input.nextInt();
} while (base != 2 && base != 4 && base != 8);
printConvertedNumber(number, base);
System.out.println();
}
private static void printConvertedNumber(int num, int base)
{
// Where i need to use recursion
}
}
Upvotes: 1
Views: 112
Reputation: 159215
I will show you a pseudo call flow that will do it for a base 10 number.
printConvertedNumber(1234, 10)
printConvertedNumber(123, 10)
printConvertedNumber(12, 10)
printConvertedNumber(1, 10)
print(1)
print(2)
print(3)
print(4)
Each invocation optionally makes a recursive call, followed by a print statement that prints the last digit of the incoming number, in the given base.
Result: 1234
was printed.
Upvotes: 1