Convert Decimal to Binary Using While Loop in C Programming


This program is written in the C programming language and it converts a decimal (base 10) number to its binary (base 2) equivalent.

The program starts by including the standard input/output header file, "stdio.h". Then, the main() function is defined. Inside the main function, three variables are declared: "n" for the decimal number to be converted, "r" for the remainder when the number is divided by 2, "m" to keep track of the place value of each digit in the binary number, and "bin" to store the binary equivalent of the decimal number.

The program then prompts the user to enter a decimal number and stores the value in the "n" variable using the scanf() function. The while loop is then used to repeatedly divide the "n" by 2, and the remainder of each division is added to "bin" after multiplying it by "m", which is initially set to 1. The "m" variable is then multiplied by 10 to prepare for the next digit in the binary number. The value of "n" is also updated to be the quotient of the previous division.

Finally, the program prints the binary equivalent of the decimal number, stored in the "bin" variable, using the printf() function and then the program is exited by returning 0 from main.

Source Code

#include<stdio.h>
int main()
{
  int n,r,m=1,bin=0;
  printf("\nEnter the Number : ");
  scanf("%d",&n);
  while(n!=0)
  {
    r=n%2;
    bin=bin+(r*m);
    m=m*10;
    n=n/2;
  }
  printf("\nBinary Value : %d",bin);
  return 0;
}
            
To download raw file Click Here

Output

Enter the Number :12
Binary Value: 1100

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C