Algorithm


Algorithm to Convert Octal to Decimal:

  1. Input:

    • Take an octal number as input.
  2. Initialize Variables:

    • Initialize a variable decimal to store the decimal equivalent.
    • Initialize a variable base to 1 (initial power of 8).
    • Parse the octal number from right to left.
  3. Convert Octal to Decimal:

    • For each digit from right to left:
      • Multiply the digit by the current power of 8 (base).
      • Add the result to the decimal variable.
      • Increment the power of 8 for the next digit.
  4. Output:

    • The decimal variable now holds the decimal equivalent of the octal number.

Algorithm to Convert Decimal to Octal:

  1. Input:

    • Take a decimal number as input.
  2. Initialize Variables:

    • Initialize a variable octal to store the octal equivalent.
    • Initialize a variable rem to 0 (remainder).
  3. Convert Decimal to Octal:

    • Repeat the following steps until the decimal number is greater than 0:
      • Calculate the remainder (rem) when the decimal number is divided by 8.
      • Append the remainder to the left of the octal variable.
      • Update the decimal number to be the quotient of the division.
  4. Output:

    • The octal variable now holds the octal equivalent of the decimal number.

 

Code Examples

#1 Code Example- Program to Convert Decimal to Octal

Code - Java Programming

public class DecimalOctal {

    public static void main(String[] args) {
        int decimal = 78;
        int octal = convertDecimalToOctal(decimal);
        System.out.printf("%d in decimal = %d in octal", decimal, octal);
    }

    public static int convertDecimalToOctal(int decimal)
    {
        int octalNumber = 0, i = 1;

        while (decimal != 0)
        {
            octalNumber += (decimal % 8) * i;
            decimal /= 8;
            i *= 10;
        }

        return octalNumber;
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
78 in decimal = 116 in octal

#2 Code Example- Program to Convert Octal to Decimal

Code - Java Programming

public class OctalDecimal {

    public static void main(String[] args) {
        int octal = 116;
        int decimal = convertOctalToDecimal(octal);
        System.out.printf("%d in octal = %d in decimal", octal, decimal);
    }

    public static int convertOctalToDecimal(int octal)
    {
        int decimalNumber = 0, i = 0;

        while(octal != 0)
        {
            decimalNumber += (octal % 10) * Math.pow(8, i);
            ++i;
            octal/=10;
        }

        return decimalNumber;
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
116 in octal = 78 in decimal
Advertisements

Demonstration


Java Programing Example to Convert Octal Number to Decimal and vice-versa-DevsEnv