Explore
ProGrad Programs
Placement Prep
TCS Codevita
Webinars
About Us

Edit
Reply




Edit

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

Published on 10 Mar 2020

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


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,

15 / 2 = 7, rem = 1
7 / 2 = 3 , rem = 1
3 / 2 = 1 , rem = 1
1 / 2 = 0 , rem = 1

Binary equivalent of 15 is 1111.

decimal to binary

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.


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


C
C++
Java

Output
Input- Enter a decimal number:255 Output- Equivalent binary number: 11111111


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>
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
long int binary = 0;
int remainder, i, flag = 1;
for(i = 1; n != 0; i = i * 10)
{
remainder = n % 2;
n /= 2;
binary += remainder * i;
}
printf("Equivalent binary number: %d", binary);
}


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


C
C++
Java
Python 3

Output
Input- Enter a decimal number:255 Output- Equivalent binary number: 11111111


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.


C
C++
Java

Output
Input- Enter a decimal number:255 Output- Equivalent binary number: 11111111


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 the reverse order.


C
C++
Java

Output
Input- Enter a decimal number:255 Output- Equivalent binary number: 11111111


Time complexity: O(n)


Recommended Programs






If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in