My simple program fails to convert 7 to 111 (the current code gives 101). I know myArray[]
and the last printf()
can be improved, but we can talk about that next time.
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3];
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
while(quo != 1){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
} myArray[i] = quo;
printf("\nBinary: %d %d %d", myArray[i + 2], myArray[i + 1], myArray[i] );
return 0;
}
i
?i + 1
(andi + 2
) be out of bounds?printf
. Thestdout
file stream (which is whatprintf
writes to) is by default line buffered. That means the output will actually be written when there is a newline in the string. If you have a leading newline you print the previous output, while the current output from the currentprintf
call will not be printed. Make it a habit to always have a trailing newline in yourprintf
calls.