Convert Octal to Decimal number in C, C++, Java and python
Program to convert a number from octal to decimal is discussed here. Given an octal number, convert the given octal number into its equivalent decimal number.
For example, octal number 1907 has to be converted to decimal.
7 * 8^0 = 7
0 * 8^1 = 0
9 * 8^2 = 576
1 * 8^3 = 512
512 + 576 + 0 + 7 = 1095
The decimal equivalent of octal number 1907 is 1095.
Algorithm to convert a number from octal to decimal
Input the octal number.
Find the number of digits in the number.
Let it have n digits.
Multiply each digit in the number with 8n-1, when the digit is in the nth position.
Add all digits after multiplication.
Program to convert a number from octal to decimal
C
#include
#include
long int octal_to_decimal(int octal)
{
int decimal = 0, i = 0;
while(octal != 0)
{
decimal += (octal) * pow(8,i); // multiplying with powers of 8
++i;
octal/=10; // Divide by 10 to make it as decimal
}
i = 1;
return decimal;
}
int main()
{
int octal;
printf(“\nEnter an octal number: “);
scanf(“%d”, &octal);
printf(“\nDecimal Equivalent : %d\n”,octal_to_decimal(octal));
return 0;
}
C++
#include
using namespace std;
long int octal_to_decimal(int octal)
{
int decimal = 0, i = 0;
while(octal != 0)
{
decimal += (octal) * pow(8,i); // multiply with powers of 8
++i;
octal/=10;
}
i = 1;
return decimal;
}
int main()
{
int octal;
cout << “\nEnter an octal number: “;
cin >> octal;
cout << “\nDecimal Equivalent : ” << octal>
return 0;
}
JAVA
import java.util.*;
public class Main
{
public static int octal_to_decimal(int octal)
{
int decimal = 0, i = 0;
while(octal != 0)
{
decimal += (octal) * Math.pow(8,i);
++i;
octal/=10;
}
i = 1;
return decimal;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the octal number : “);
int octal = sc.nextInt();
System.out.print(“\nEquivalent decimal number : ” + octal_to_decimal(octal));
}
}
PYTHON 3
import math
def octal_to_decimal(octal):
decimal = 0
i = 0
while(octal != 0):
decimal += (octal) * math.pow(8,i)
i = i + 1
octal = int(octal / 10)
i = 1;
return decimal
octal = int(input(“Enter the octal number : “))
print(“Equivalent decimal number : “,int(octal_to_decimal(octal)))
Output
Input- Enter an octal number: 350 Output- Decimal Equivalent :232
Time complexity:O(n)
Write a public review