Write a java program to convert a decimal number to its corresponding octal representation.
Example:
1 2 3 4 5 |
Input: 7 Output: 7 Input: 8 Output: 10 |
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.
Let’s implement the same in Java.
Convert Decimal to Octal in Java using While Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); //Input the decimal number System.out.println("Enter a Decimal Number"); int decimal = in.nextInt(); int octal=0, i=1; //While loop will run until 'decimal' becomes 0 on dividing it by 8 while(decimal>0){ octal += i*(decimal%8); //adding the remainder on left of octal decimal = decimal/8; //update i, so that on next iteration, rem will be added to left of octal i=i*10; } System.out.println("Octal: "+octal); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); //Input the decimal number System.out.println("Enter a Decimal Number"); int decimal = in.nextInt(); System.out.print("Octal: "); decToOctal(decimal); } private static void decToOctal(int n){ if(n>0){ //recall by passing quotient decToOctal(n/8); //print remainder System.out.print(n%8); } } } |
Output
Enter a Decimal Number
8
Octal: 10
If you have any suggestions or doubts then comment below.