Python Program to Print Binary Equivalent of a Number without Using Recursion

This is a Python Program to find the binary equivalent of a number without using recursion.

Problem Description

The program takes a number and finds the binary equivalent of the number without using recursion.

Problem Solution

1. Take a number from the user.
2. Using a while loop, convert each digit into binary and append it to the list.
3. Reverse the list and using a for loop print the elements of the list.
4. Exit.

Program/Source Code

Here is source code of the Python Program to find the binary equivalent of a number without using recursion. The program output is also shown below.

n=int(input("Enter a number: "))
a=[]
while(n>0):
    dig=n%2
    a.append(dig)
    n=n//2
a.reverse()
print("Binary Equivalent is: ")
for i in a:
    print(i,end=" ")
Program Explanation

1. User must enter a number.
3. The condition for the while loop is that the number should be greater than 0.
4. Otherwise, each digit is converted into binary and appended to the list.
5. The list is reversed and a for loop is used to print the elements of the list which is the binary equivalent of the number.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter a number: 2
Binary Equivalent is: 
1 0 
 
Case 2:
Enter a number: 7
Binary Equivalent is: 
1 1 1

Sanfoundry Global Education & Learning Series – Python Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.