Home C Examples C Program to Convert Decimal Number to Binary Number

C Program to Convert Decimal Number to Binary Number

by anupmaurya

In this tutorial, we will write a C Program to Convert Decimal Number to Binary Number. To convert decimal number to binary number divide a decimal number by two, if the quotient is not zero again divided it by two and keep dividing it by two until the quotient is equal to zero.

#include<stdio.h>

int main(){
    int n = 4;
    int rem;
    int a[10];
    int i=0;
    while(n){
        rem = n%2;
        n = n/2;
        a[i] = rem;
        i++;
    }

    for (int j = i-1; j >=0; j--)
    {
        printf("%d", a[j]);
    }
    
    return 0;
}
  • We have initialized an integer variable “n” which has value “4” this program will convert decimal number “4” to binary number.
  • We have declared an integer variable “rem” which has stored the remainder
  • We have declared an array “a” of the size [10] and initialized an integer variable “i” which has value “0”
  • The “while” loop will run till the value of “n” gets “0”.
  • In the “while” loop body the modulus “n%2” is taken and the value is stored in the variable “rem”; in the next step the value of “n” is divided by “2” and the value is stored in the variable “n”; in next step, the value of the variable “rem” is stored at the “i” index of an array and the value of the “i” is incremented.
  • The main thing to note here is that the values of the remainder stored in the array are opposite that’s why we have to print them in reverse order for that we have used “for” loop.
  • The “for” will start from the value “i-1” and runs till the values of “j” becomes greater than or equal to “0”; in the “for” loop body array is printed using “scanf” function.

Output of C Program to Convert Decimal Number to Binary Number

// As n=4
100

100 is a binary of 4.

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.