Convert from decimal to binary in C

2

I'm making a C code for a college job with the goal of converting a decimal number to binary. But when the program runs, it always prints 00000000, no matter what number I put. Could anyone tell you what the mistake is? Here is the code:

#include <stdio.h>
#include <stdlib.h>

int main() {

    int num;
    int bin[7];
    int aux;

    printf("Digite o número (base decimal) para ser convertido: ");
    scanf("%d", &num);

    for (aux = 7; aux >= 0; aux--) {
        if (num % 2 == 0) {
            bin[aux] = 0;
            num = num / 2;
        }
        else {
            bin[aux] = 1;
            num = num / 2;
        }
    }

    for (aux = 0; aux <= 7; aux++) {
        printf("%d", bin[aux]);
    }

    return 0;
}
    
asked by anonymous 21.04.2017 / 15:54

1 answer

0

I could not reproduce the reported error, but it has an error in the declaration of array "bin", which by its logic must have 8 elements. Other than that, there does not seem to be anything wrong.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int num;
   int bin[8]; // <---------------
   int aux;

   printf("Digite o número (base decimal) para ser convertido: ");
   scanf("%d", &num);

   for (aux = 7; aux >= 0; aux--)
   {
      if (num % 2 == 0)
         bin[aux] = 0;
      else
         bin[aux] = 1;
      num = num / 2;
   }

   for (aux = 0; aux < 8; aux++)
       printf("%d", bin[aux]);

   printf("\n");

   return 0;
}
    
21.04.2017 / 21:43