In this article, we will understand how to convert decimal to octal. a Decimal number is a number whose whole number part and the fractional part is separated by a decimal point. Octal Number has a base of eight and uses the number from 0 to 7.
Below is a demonstration of the same −
Input
Suppose our input is −
Enter the decimal number : 8
Output
The desired output would be −
The octal value is 10
Algorithm
Step 1 - START Step 2 - Declare three integer value namely my_input, I and j and an integer array my_octal Step 3 - Read the required values from the user/ define the values Step 4 – Using a while condition of input not equal to 0, compute my_input % 8 and store it to my_octal[i] Step 5 - Compute my_input / 8 and assign it to ‘my_input’, increment ‘i’ value. Step 6 – Iterating using a for loop, print the ‘my_octal’ array Step 7- Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool
.
import java.util.Scanner;
public class DecimalToOctal {
public static void main(String[] args){
int my_input, i, j;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the decimal number : ");
my_input = my_scanner.nextInt();
int[] my_octal = new int[100];
System.out.println("The octal value is ");
i = 0;
while (my_input != 0) {
my_octal[i] = my_input % 8;
my_input = my_input / 8;
i++;
}
for ( j = i - 1; j >= 0; j--)
System.out.print(my_octal[j]);
}
}Output
Required packages have been imported A reader object has been defined Enter the decimal number : 8 The octal value is 10
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class DecimalToOctal {
public static void main(String[] args){
int my_input, i, j;
my_input = 8;
System.out.println("The decimal number is defined as " +my_input);
int[] my_octal = new int[100];
System.out.println("The octal value is ");
i = 0;
while (my_input != 0) {
my_octal[i] = my_input % 8;
my_input = my_input / 8;
i++;
}
for ( j = i - 1; j >= 0; j--)
System.out.print(my_octal[j]);
}
}Output
The decimal number is defined as 8 The octal value is 10