Problem: Write a Java program to convert octal into its corresponding decimal representation.
Example:
Input: 14 Output: 12 Input: 5 Output: 5
Method 1: Using While Loop
To convert octal into a decimal, we multiply the digits of the octal with their respective exponential value of 8 (8position from the right – 1) and sum them up.
In Java, we use while loop to iterate through the digits as follows:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i=0, decimal=0, digit;
//Input an Octal Number
System.out.println("Enter a Octal Number");
int octal = in.nextInt();
while(octal>0){
//extract digit
digit = octal%10;
//multiply with exponential of 8 and add to the decimal
decimal += Math.pow(8,i++)* digit;
//remove digit from the octal number
octal = octal/10;
}
//output the octal number
System.out.println("Decimal: "+decimal);
}
}
Output:
Enter a Octal Number
14
Decimal: 12
Method 2: Using Recursion
The approach used in this method is the same as the above program but is implemented in a recursive fashion.
In each recursive call, we extract the digit from the octal number, multiply it with its respective exponential value of 8 and return its sum with the next recursive call’s result.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Input an Octal Number
System.out.println("Enter a Octal Number");
int octal = in.nextInt();
//call the recursive function and output the returned result
System.out.println("Decimal: "+octalToDec(octal,0));
}
//'i' represents the nth recursive call as well as the
//(n-1)th digit from left, so it can be used as an exponent
private static int octalToDec(int oct, int i){
//base condition
if(oct == 0)
return 0;
//extract digit
int digit = oct%10;
//multiply with exponential of 8 and add with next recusive call
return (int)Math.pow(8,i)*digit + octalToDec(oct/10, ++i);
}
}
Output:
Enter a Octal Number
10
Decimal: 8
It is important to note that in the recursive call statement, we pass the octal value by eliminating the digit which has been processed in the current recursive call.