0% found this document useful (0 votes)
24 views2 pages

C

The document contains code for a C program that converts decimal numbers to binary. The program uses a while loop to continuously take in decimal numbers from the user and output the corresponding binary numbers.

Uploaded by

Numan Mahzabin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views2 pages

C

The document contains code for a C program that converts decimal numbers to binary. The program uses a while loop to continuously take in decimal numbers from the user and output the corresponding binary numbers.

Uploaded by

Numan Mahzabin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <math.h>
int main()
{
printf("\n\n\t\t\tDecimal to Binary Converter\n\n\n");
int decimal, power, temp_answer, i;
char binary[20];

while (1)
{
printf("\nDecimal : ");
scanf("%d", &decimal);
printf("\n");
if (decimal == 'x')
{
return 0;
}
if (decimal == -1)
{
printf("\nThanks for using our program\n");
return 0;
}
else if (decimal == 0)
{
power = 0;
}
else if (decimal > 0)
{
for (i = 0; pow(2, i) <= decimal; i++)
{
power = i;
}
}
else if (decimal < 0)
{
printf("\nplease type postive decimal number. Sorry this is not able
to convert negative decimal to binary\n");
continue;
}

temp_answer = 0;
for (i = 0; power >= 0; i++)
{
if (decimal >= (temp_answer + pow(2, power)))
{
temp_answer = temp_answer + pow(2, power);
binary[i] = '1';
}
else
{
binary[i] = '0';
}
power--;
}
binary[i] = '\0';

printf("\nBinary : %s\n\n", binary);


}
return 0;
} // 11

You might also like