Search code examples
cradix

Having trouble converting a decimal into a binary in C. No output


Normally this would be easy, but I just started learning C. I'm using visual studio 2017 community and right now I don't seem to be able to use watches. When I run the program it outputs nothing. What did I do wrong?

//20_10_17
//Crehul Vlad
//Base conversion: Decimal into Binary
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

void main() {
    int k=0, i, r, nr, c, N[64];
    printf("Decimal Nr: "); scanf("%d", &nr);
    c = nr;
    while (nr % 2 != 0) {
        r = c % 2;
        c = c / 2;
        N[k] = r; k++;
    }
    for (i = k; i > 0; i--) {
        printf("%d ", N[i]);
    }

_getch();
return 0;
}

Solution

  • int main()
    {
        int k=0, i, r, nr, c, N[64];
        printf("Decimal Nr: "); scanf("%d", &nr);
        c = nr;
        if(nr==0)
          printf("0");
        else{
        while (nr) {
            r = nr % 2;
            nr = nr / 2;
            N[k] = r; k++;
          }
        }
        // original number in variable c
        for (i = k-1; i >= 0; i--) {
            printf("%d ", N[i]);
        }
        return 0;
    }
    

    Just try to understand what the algorithm does. And be careful when you code terminating conditions.