Skip to content

Commit 21dab04

Browse files
author
Christian Bender
authored
fixed a bug and refactoring
If user type in 0 the output was empty. This bug is fixed. In addition I refactored and documented the code.
1 parent b79f0c1 commit 21dab04

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

conversions/decimal _to_binary.c

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
#define MAXBITS 100
5+
6+
int main()
7+
{
8+
9+
// input of the user
10+
int inputNumber;
11+
12+
// for the remainder
13+
int re;
14+
15+
// contains the bits 0/1
16+
int bits[MAXBITS];
17+
18+
// for the loops
19+
int j;
20+
int i=0;
21+
22+
printf("\t\tConverter decimal --> binary\n\n");
23+
24+
// reads a decimal number from the user.
25+
printf("\nenter a positive integer number: ");
26+
scanf("%d",&inputNumber);
27+
28+
// make sure the input number is a positive integer.
29+
if (inputNumber < 0)
30+
{
31+
printf("only positive integers >= 0\n");
32+
return 1;
33+
}
34+
35+
// actual processing
36+
while(inputNumber>0)
37+
{
38+
39+
// computes the remainder by modulo 2
40+
re = inputNumber % 2;
41+
42+
// computes the quotient of division by 2
43+
inputNumber = inputNumber / 2;
44+
45+
bits[i] = re;
46+
i++;
47+
48+
}
49+
50+
printf("\n the number in binary is: ");
51+
52+
// iterates backwards over all bits
53+
for(j=i-1; j>=0; j--)
54+
{
55+
printf("%d",bits[j]);
56+
}
57+
58+
// for the case the input number is 0
59+
if (i == 0)
60+
{
61+
printf("0");
62+
}
63+
64+
return 0;
65+
}
66+

0 commit comments

Comments
 (0)