Convert a number from decimal to binary in C, C++, Java and Python | faceprep

Convert a number from decimal to binary in C, C++, Java and Python | faceprep

Programs to convert a number from decimal to binary can be done using four methods.


convert-a-number-from-decimal-to-binary-faceprep

Method 1: Using for loop

Method 2: Using while loop

Method 3: Using Stack

Method 4: Using Array


For example, the binary equivalent of decimal number 15 is 1111. The decimal number 15 is recursively divided by 2 until it cannot be divided any further. In each of these cases, the remainder is to be noted. The reverse of the remainder gives the binary equivalent of the decimal number. Let us now look at an example to understand this better.


Considering the same example,nn15 / 2 = 7, rem = 1n7 / 2 = 3 , rem = 1n3 / 2 = 1 , rem = 1n1 / 2 = 0 , rem = 1nnBinary equivalent of 15 is 1111.n



convert-a-number-from-decimal-to-binary-faceprep

Algorithm

  • Input the decimal number.
  • Divide the number by 2 and store the remainder.
  • Repeat step 2 until the number cannot be divided any further
  • Print the remainder in a reversed order.



convert-a-number-from-decimal-to-binary-faceprep

Program to convert a number from decimal to binary using for loop

@@coding::1@@


Command line

The given number N, a positive integer, will be passed to the program using the first command line parameter. Print the equivalent binary number to stdout. Other than the binary number, no other extra information should be printed to stdout Example: Given input 19, here N=19, expected output 10011


Solution:

#include <stdio.h>nint main(int argc, char *argv[])n{nint n = atoi(argv[1]);nlong int binary = 0;nint remainder, i, flag = 1;nfor(i = 1; n != 0; i = i * 10)n{nremainder = n % 2;nn /= 2;nbinary += remainder * i;n}nprintf("Equivalent binary number: %d", binary);n}n


Program to convert a number from decimal to binary using while loop


@@coding::2@@


Program to convert a number from decimal to binary using Stack

In this method, the decimal value is divided by 2 and the remainder is stored in a stack. Once the decimal value reaches zero, print the values stored in the stack.

@@coding::3@@



convert-a-number-from-decimal-to-binary-faceprep


Program to convert a number from decimal to binary using an Array


Divide the decimal value by 2 and store the remainder in the array. Once the decimal value reaches zero, print the array values in reverse order.


@@coding::4@@


Time complexity: O(n)


Recommended Programs








convert-a-number-from-decimal-to-binary-faceprep

c