Java Program to convert octal number to decimal number

Here we are explaining how to write a java program to convert octal numbers to decimal numbers.

What is the octal number?

The octal number uses eight digits. The digits are 0 to 7.An octal number is formed by grouping three consecutive binary numbers.

Example:Decimal 9 =11 in Octal

              Decimal 7=7 in Octal

How to implement the java program to convert octal numbers to decimal numbers in java?

First, we have to declare the class OctToDec.Create an object of the scanner class as sc. Read the octal number from the user into the variable oct.Keep the octal number into another integer variable oct1. Declare the integer variables n,p.Set n=0,p=0.By using while loop checks if oct=0 if true then break from the loop.Else set temp=oct,n=n+temp*Math.pow(8,p).Calculate oct=oct/10.Increment p by one and repeat the process until oct becomes zero. Now the variable n contains the decimal equivalent of the octal number. Then display it by using the system.out.println.

ALGORITHM

STEP 1: Declare the class OctToDec with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Create an object of the scanner class as sc.

STEP 4: Read the octal number from the user into the variable oct.

STEP 5: Assign oct1=oct.

STEP 6: Declare n,p as an integer.

STEP 7: Set n=0,p=0.

STEP 8: by using while loop checks if oct=0 is true then break else do step 9.

STEP 9: Assign temp=oct,n=n+temp*Math.pow(8,p).

STEP 10: Calculate oct=oct/10 and increment p by one.

STEP 11: Repeat step 8.

STEP 12: Display the decimal equivalent of the octal number as n.

 

Java Source Code

                                          import java.util.Scanner;
public class OctToDec{  
   public static void main(String args[]){  
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter the octal number:");
int oct= sc.nextInt();
int oct1=oct;
   int n,p;    
   n=0;
   p=0;

 while(true){    
    if(oct == 0){    
  break;    
    } else {    
  int temp = oct;    
  n += temp*Math.pow(8, p);    
  oct = oct/10;    
  p++;    
    }    
 } 
    
 System.out.println("The Decimal Equivalent of the octal number "+oct1+" is " +n);
   }
}
                                      

OUTPUT

Enter the octal number:
65
The Decimal Equivalent of the octal number 65 is 113