Write a Program in Python to convert a decimal number into its corresponding octal representation.

Example:

Input:  8
Output: 10

Input:  15
Output: 17

Decimal to Octal

Recommended:

Convert Decimal to Octal in Python using Loop

The standard way to convert a decimal to octal is to divide the decimal by 8 until it reduces to 0. The remainders in the bottom-up form will give its equivalent octal value.

decimal = int(input("Enter a decimal number \n"))
octal = 0
ctr = 0
temp = decimal  #copying number
 
#calculating octal
while(temp > 0):
    octal += ((temp%8)*(10**ctr))  #Stacking remainders
    temp = int(temp/8)             #updating dividend
    ctr += 1
       
print("Binary of {x} is: {y}".format(x=decimal,y=octal))

Output

Enter a decimal number                                                                                                        
15                                                                                                                            
Binary of 15 is: 17

Convert Decimal to Octal in Python using Recursion

To convert decimal into octal using recursion we need to pass the quotient (dividend/8) to the next recursive call and print the remainder (dividend%8).

Since recursion implements stack so the remainder will be printed in a bottom-up manner.

def dectoOct(decimal):
    if(decimal > 0):
        dectoOct((int)(decimal/8))
        print(decimal%8, end='')
        
decimal = int(input("Enter a decimal number \n"))
print("Octal: ", end='')
dectoOct(decimal);

Output

Enter a decimal number                                                                                                        
8                                                                                                                             
Octal: 10

Convert Decimal to Octal using oct()

Python inbuilt oct() method return the octal form of a passed number as a parameter.

It returns octal number in the form of 0oxxx, where xxx is the number form of octal representation.

print(oct(15))

Output

0o17

Comment below your doubts or suggestions if you have any.

Leave a Reply

eighteen − thirteen =