Decimal to Binary using strings

Hi, im trying to get my program to convert from decimal to binary (in the second part) but when I compile it I keep getting 0, I know I have to divide it by 2 using % and keep it in the loop but Im not sure how to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{

 char string[100];
 int s;
 char a;
 char j;
 int sum = 0;
 int r;
 int q;

 printf("B = B to D\n");
 printf("D = D to B\n");
 printf("choose which one to convert to:");
 scanf("%c%c", &a, &j);

 if (a == 'B')
 {
        printf("enter binary number to convert to decimal: ");
        scanf("%s", string);

        for(s = strlen(string)-1; s >= 0; s--)
        {

                if(string[s] == '1')
                {
                sum = sum + pow(2, strlen(string) - (s +1));

                }
        }
 printf("the decimal number is: %d\n", sum);
 }

 if (a == 'D')
 {
        printf("enter decimal number to convert to binary: ");
        scanf("%s", string);

        while (r > 0)
        {
        r = q%2;
        q = q%2;
        }

 printf("the binary number is: %d\n", r);

 }

 return 0;
}


Last edited on
Well, your while loopsupposedly doing the conversion involves r and q, which are never set to anything. You should probably take the user's input into string and use it to populate r and q.
well r and q are gonna be the remainder and quoteint from dividing the string by 2 but im not sure how to do that in the first place....
Topic archived. No new replies allowed.