1

I'm trying to make a code for converting decimal into binary for n<16 without using iteration. but the output is always either 1000, 100, 10 or 1. what is wrong with the code? thank you very much

#include <stdio.h>

int main(void){
int decimal, bin = 0;
printf("Enter number to convert to base 2: ");
scanf("%d", &decimal);

if(decimal >= 8){
    bin += 1000;
    decimal = decimal%8;
}else if(decimal >= 4){
    bin += 100;
    decimal = decimal%4;
}else if(decimal >= 2){
    bin += 10;
    decimal = decimal%2;
}else if(decimal >= 0){
    bin += decimal%2;
}
printf("%5d", bin);
;
}
Imran Ariffin
  • 185
  • 1
  • 8

1 Answers1

1

Drop the else's. The tests must apply successively. If only one applies of course you get only a power of 2.

Of course, representing binary numbers as decimals is a really bad idea -- but for printing purposes only it would work.

dan3
  • 2,528
  • 22
  • 20