For 4 binary is 100 For 21 binary is 10101 Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import java.util.Scanner; public class DecToBin{ public static void main (String []args){ Scanner sc = new Scanner(System. in ); System. out . println ( "Enter a decimal value:" ); int decimal = sc. nextInt (); int binary = 0 , i = 1 ; while (decimal!= 0 ){ binary += (decimal % 2 ) * i; i = i * 10 ; decimal = decimal / 2 ; } System. out . println ( "Binary value:" +binary); } } Python decimal = int ( input ( "Enter a decimal value:" )) binary, i = 0 , 1 while decimal != 0 : binary += (decimal % 2 ) * i i = i * 10 decimal = decimal // 2 print ( "binary value :" ,binary)
This blog contains coding/programming and interview questions of MNCs like TCS, Wipro, Infosys, Capgemini, Mindtree, Amazon, Google, Facebook, Flipkart, Cisco, HP, Dell, etc. with placement preparation guides.