My array printf loop is missing one digit at the end

Viewed 100

I'm trying to convert decimal to binary via this program, but the output is always missing the last digit.

For example, I'll input "123" for quotient, and the result will be "111101" instead of "1111011". This happens for every input I test. Every digit is in the right place, except for the last one, which is missing.

Any help would be appreciated.

#include <stdio.h>
int main ()
{
    int quotient = 123;
    int i = 0;
    int d1 = quotient % 2;
    quotient = quotient / 2;
    int c = 0;
    int a = 0;
    int number[32] = {};

    while (quotient != 0)
    {
        i = i+1;
        d1 = quotient % 2;
        quotient = quotient / 2;
        c++;
        number[c]=d1;
    }

    for(a = 0; a < c; a = a + 1 )
    {
        printf("%d", number[c-a]);
    }
    return 0;
}
2 Answers

The problem is that you're dividing once before the while loop :

int d1 = quotient % 2;
quotient = quotient / 2;

Replace that with just :

int d1 = 0;

and things should work better.

You have the following problems in your code

  1. should be handled in while loop.

    int d1 = quotient % 2; quotient = quotient / 2;

  2. You are incrementing the c before putting into the array.

  3. Your printf is wrong printf("%d", number[c-a]); should be printf("%d", number[c-a-1]);

Your full code

#include <stdio.h>

int main (){
  int quotient = 15;
  int i = 0;
  int d1;
  //quotient = quotient / 2;
  int c = 0;
  int a = 0;
  int b = 0;
  int number[32] = {};

  while (quotient != 0){
     d1 = quotient % 2;
     quotient = quotient / 2;
     number[c]=d1;
    printf("%d\n", number[c]);
     c++;
  }
  for(a = 0; a < c; a = a + 1 ){
    printf("%d", number[c-a-1]);
  }
  return 0;
}
Related