Java: Convert a octal number to a decimal number
Java Basic: Exercise-25 with Solution
Write a Java program to convert a octal number to a decimal number.
Octal number: The octal numeral system is the base-8 number system, and uses the digits 0 to 7.
Decimal number: The decimal numeral system is the standard system for denoting integer and non-integer numbers. It is also called base-ten positional numeral system.
Test Data:
Input any octal number: 10
Pictorial Presentation: Octal to Decimal number
Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise25 {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner in = new Scanner(System.in);
// Declare variables to store octal and decimal numbers, and an index counter
long octal_num, decimal_num = 0;
int i = 0;
// Prompt the user to input an octal number
System.out.print("Input any octal number: ");
octal_num = in.nextLong();
// Convert the octal number to decimal
while (octal_num != 0) {
decimal_num = (long)(decimal_num + (octal_num % 10) * Math.pow(8, i++));
octal_num = octal_num / 10;
}
// Display the equivalent decimal number
System.out.print("Equivalent decimal number: " + decimal_num + "\n");
}
}
Explanation:
In the exercise above -
- First, it takes an octal number as input from the user using the "Scanner" class and stores it in the variable 'octal_num'.
- It initializes a variable 'decimal_num' to store the decimal equivalent and another variable 'i' to keep track of the position of each octal digit.
- It enters a loop to perform the octal-to-decimal conversion:
- In each iteration, it calculates the remainder when 'octal_num' is divided by 10 (which gives the least significant octal digit).
- It multiplies this remainder by 8 raised to the power of 'i' and adds it to 'decimal_num' to accumulate the decimal value.
- To move to the next octal digit, it increments i.
- It updates 'octal_num' by removing the least significant digit (rightmost) by dividing it by 10.
- The loop continues until 'octal_num' becomes zero, effectively converting the entire octal number to decimal.
- After the loop, it prints the decimal representation of the original octal number stored in the ‘decimal_num’ variable.
Sample Output:
Input any octal number: 10 Equivalent decimal number: 8
Flowchart:
Java Code Editor:
Previous: Write a Java program to convert a binary number to a Octal number.
Next: Write a Java program to convert a octal number to a binary number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/java-basic-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics