#include <stdio.h>
#include <stdlib.h>
// Print out the binary value of an integer
void binval (int num);
int get_number();
main () {
int num;
num = get_number();
printf("Num = %d\n",num);
binval(num);
}
void binval (int num) {
int val = 0;
int test;
if (!num) {
printf("\n");
return;
}
test = num & 0x0001;
if (test == 1) {
val = 1;
}
num = num / 2;
printf("%d",val);
binval(num);
return;
}
int get_number() {
int value = 0;
char c;
printf("Please input number : ");
while ((c = getchar()) != '\n') {
if ( (c>'9') || (c<'0') ) {
printf("Incorrect character entered as a number - %c\n",c);
exit(-1);
}
else {
value = 10*value + c - '0';
}
}
return(value);
}
now it compiles just get 01 for every answer.
The call to
binvalinmainimplicitly declares it likeint binval(int).In order to fix that, you’ll need to either add a forward declaration for
binval, or movemainto afterbinval.After that, and after fixing the other stuff mentioned in other answers, we still have one little problem: the bits will be printed out backwards, because you’re printing the least significant bit first. The easiest way to fix that is to switch the
binvalandprintfwithin thebinvalfunction itself, but of course you probably won’t want the base case (num==0) to print a newline. Just print a newline after you call the function frommain.