Write a program to convert Octal to Decimal number system


The program first declares a Scanner object to read input from the user. It then declares a long variable oct to store the octal number entered by the user, and a long variable dec to store the decimal equivalent. It also declares an int variable i to keep track of the position of each digit in the octal number. The program then prompts the user to enter an octal number, reads it using the Scanner object, and prints the octal number.

Next, the program enters a loop that performs octal to decimal conversion. It uses the modulo operator % to obtain the rightmost digit of the octal number oct and multiplies it by 8 raised to the power of i. It then updates the decimal equivalent dec by adding this result to it. It also increments i to move to the next digit of the octal number, and divides oct by 10 to remove the processed digit. The loop continues until the octal number becomes 0.

Finally, the program prints the decimal equivalent of the octal number using System.out.print(). Note that there is no space or newline character after the decimal number, so it will be printed immediately after the text "Decimal Number: ".

Source Code

import java.util.Scanner;
public class Octal_Decimal
{ 
	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		long oct, dec = 0;
		int i = 0;
		System.out.print("Enter The Octal Number: ");
		oct = input.nextLong();
		System.out.println("Octal Number: " + oct);
		while (oct != 0) 
		{
		dec = (long)(dec + (oct % 10) * Math.pow(8, i++));
		oct = oct / 10;
		}
		System.out.print("Decimal Number: " + dec);
	}
}
 

Output

Enter The Octal Number: 14
Octal Number: 14
Decimal Number: 12

Example Programs