Write a java program to convert a decimal number to its corresponding octal representation.

Example:

The standard way of converting a number from the decimal number system to the octal number system is to divide the decimal number by 8 until the number reduces to 0 using while loop.

In the meantime, we also have to concatenate each remainder according to the bottom-up approach (i.e to the left of the concatenated remainders).

The following picture describes how a decimal is converted to octal.

Decimal to Octal

Let’s implement the same in Java.

Convert Decimal to Octal in Java using While Loop

Output

Enter a Decimal Number
15
Octal: 17

Convert Decimal to Octal in Java using Recursion

In this method, we will use recursion to convert the decimal number into its octal representation. Since recursion implements stack so the remainder will start printing from the last recursive call, hence we will get the output of remainders (divisible by 8) in the bottom-up approach.

Output

Enter a Decimal Number
8
Octal: 10

If you have any suggestions or doubts then comment below.

Leave a Reply

Close Menu