Reputation: 1
and i need to make a decimal to binery converter in c with recursion but the output is wrong ex decimal = 22, correct binary = 10110, output = 01101
so this is the code that i came up with
#include <stdio.h>
int biner (int a){
if (a == 1)
return 1;
else if (a % 2 == 1)
{
printf ("1");
return biner (a / 2);
}
else
{
printf ("0");
return biner (a / 2);
}
}
int main () {
int a;
printf ("Masukan angka ");
scanf ("%d", &a);
printf ("%d", biner (a));
}
which part do i need to change thanks in advance
Upvotes: 0
Views: 73
Reputation: 153348
OP's code output is in the wrong order as it needs to recurse before printing to print the most significant digits first.
Instead of
printf ("1"); // prints least significant digit
biner (a / 2); // prints most significant digits
More like
biner (a / 2); // prints most significant digits
printf ("1"); // prints least significant digit
There really is no need to return a value, let biner()
can do all printing.
As code is not attempting to print a sign, might as well use unsigned a
.
OP's code recurses endlessly if a == 0
. Only recurse if a >= 1
. ( a binary digit exist to the left.)
With d
as 0 or 1, The binary digit to print can use putchar('0' + d)
Suggested simplification:
#include <stdio.h>
void biner(unsigned a) {
if (a > 1) { // Do binary digits exist to the left?
biner(a/2); // Print them.
}
putchar('0' + a%2); // Now print the least significant digit.
}
int main(void) {
unsigned a;
printf("Masukan angka ");
scanf("%u", &a);
biner(a);
putchar('\n');
}
Upvotes: 1