Coders Packet

Converting decimal to binary using recursion in Python

By Omprakash Biswas

  • dtb_op.png
  • dtb_algo.png
  • decimal_to_binary_rec.py
  • The easiest way to convert a decimal number to a binary number using recursion in Python language.

    Here users will give a decimal number as an input and the output will be a corresponding binary value.

    In recursion, we must define a stopping condition, here if the passed argument value is less than or equals 1 then we return the remainder. When the input is greater than 1 the function 'decimal_to_binary' calls itself and passes the integer division value i.e. the result. When the function reaches its terminating condition i.e. the passed argument value becomes less than or equals 1, then the last function call returns the remainder to the previous function, then the previous function returns the remainder to its previous function so on and so forth.Algorithm

    Code:

    # Code for Converting decimal to binary using recursion
    def decimal_to_binary(n):
        """
        Input: An integer decimal number
        Output: A binary number corresponding to a decimal number
        """
     
        if(n > 1):
            # Integer division
            decimal_to_binary(n//2)
        # Printing the remainder after deviding by 2
        print(n%2, end="")
    
    n = int(float(input("Enter a decimal value :")))
    decimal_to_binary(n)

     

    Note: It is only valid for integers.

    Output: 

    output

    Download Complete Code

    Comments

    Comments for the packet "Converting decimal to binary using recursion in Python";
    No comments yet