Convert Octal to Decimal number in C, C++, Java and python | faceprep

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.

octal to decimal

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 8n1, when the digit is in the nth position.
  • Add all digits after multiplication.

Program to convert a number from octal to decimal

// C program to convert a number from octal to decimal

#include
#include

long int octal_to_decimal(int octal)
{
int decimal = 0, i = 0;

while(octal != 0)
{
decimal += (octal%10) * 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++ program to convert a number from octal to decimal

#include
#include using namespace std;

long int octal_to_decimal(int octal)
{
int decimal = 0, i = 0;

while(octal != 0)
{
decimal += (octal%10) * 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_to_decimal(octal) << endl;;

return 0;
}

// Java program to convert a number from octal to decimal

import java.util.*;
public class Main
{
public static int octal_to_decimal(int octal)
{
int decimal = 0, i = 0;

while(octal != 0)
{
decimal += (octal%10) * 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 program to convert a number from octal to decimal

import math
def octal_to_decimal(octal):
decimal = 0
i = 0
while(octal != 0):
decimal += (octal%10) * 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:

octal to decimal

Time complexity: O(n)