Algorithm
Algorithm to Convert Octal to Decimal:
-
Input:
- Take an octal number as input.
-
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.
- Initialize a variable
-
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.
- For each digit from right to left:
-
Output:
- The
decimal
variable now holds the decimal equivalent of the octal number.
- The
Algorithm to Convert Decimal to Octal:
-
Input:
- Take a decimal number as input.
-
Initialize Variables:
- Initialize a variable
octal
to store the octal equivalent. - Initialize a variable
rem
to 0 (remainder).
- Initialize a variable
-
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.
- Calculate the remainder (
- Repeat the following steps until the decimal number is greater than 0:
-
Output:
- The
octal
variable now holds the octal equivalent of the decimal number.
- The
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
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
116 in octal = 78 in decimal
Demonstration
Java Programing Example to Convert Octal Number to Decimal and vice-versa-DevsEnv