Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Print Binary Equivalent of an Integer using Recursion

# Python Program to Print Binary Equivalent of an Integer using Recursion

In this Python program, we will create a recursive function to print the binary equivalent of an integer. Recursion is a technique where a function calls itself to solve a smaller version of the problem. By applying recursion, we can break down the conversion of an integer to binary into smaller steps until we reach the base case.

## Problem Statement

Write a Python program to print the binary equivalent of an integer using recursion.

## Python Program to Print Binary Equivalent of an Integer using Recursion

```def decimal_to_binary(n):
if n > 1:
decimal_to_binary(n // 2)
print(n % 2, end='')

# Getting input from the user
num = int(input("Enter a decimal number: "))

# Printing the binary equivalent
print("Binary equivalent of", num, "is:", end=' ')
decimal_to_binary(num)```

## How it works

1. We define a recursive function `decimal_to_binary` that takes an integer `n` as input.
2. Inside the function, we check if `n` is greater than 1. If it is, we recursively call the `decimal_to_binary` function with `n // 2`.
3. This recursive call helps us to divide the number by 2 repeatedly until we reach the base case, which is when `n` becomes 1.
4. After the recursive call, we print the remainder of `n` divided by 2. This gives us the binary digit of the current step.
5. By using the `end` parameter of the `print` function and setting it to an empty string, we ensure that the binary digits are printed side by side without any line breaks.
6. Finally, we prompt the user to enter a decimal number, convert it to an integer using `int(input())`, and call the `decimal_to_binary` function with the input number.

## Input / Output

Share:

### You May Also Like

#### Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

#### Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

#### Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...