Problem: Write a Java program to convert a decimal number into its corresponding octal representation.

Example:

Method 1: Using While Loop

Decimal to Octal

To convert a decimal into octal we divide the decimal number by 8 until it reduces to 0 and stacks the sequence of remainders in a bottom-up manner.

In the Java program, we divide and concatenate remainders inside a while loop as follows:

Output:

Enter a Decimal Number
15
Octal: 17

To concatenate remainders in a bottom-up manner, we first multiply the remainder with 10number_of_digits_in_octal (i*10) then add it to the octal number.

Method 2: Using Recursion

We can also convert a decimal number into an octal number using the recursive approach.

To do so, we recursively call the function with the quotient value (decimal/8) and print the remainder after the recursive call.

Output:

Enter a Decimal Number
8
Octal: 10

By writing the print statement after the recursive call statement, the remainders gets printed in the bottom-up sequence.

It is so because the print action starts when the recursive function starts tracing back to its first recursive call.

Leave a Reply

5 + nine =