#include<stdio.h>
void binary(int n)
{
int bin=0;
if(n!=0)
{
bin=n%2;
binary(n/2);
}
printf("%d",bin);
}
void main()
{
int a;
printf("Decimal value: ");
scanf("%d",&a);
binary(a);
}
When I tried to run above code, it outputs the binary value of the decimal number a preceding with one 0. As I have used recursive function here, it also puts the initial value of bin (i.e. 0) on stack and prints that 0 as well. But I want to display only binary values not that preceding 0.
I would be glad if anyone suggest me how to make this function not to store that initial value of bin on stack.
Try this.
#include<stdio.h>
void binary(int n)
{
bin=n%2;
if(n/2!=0)
binary(n/2);
printf("%d",bin);
}
void main()
{
int a;
printf("Decimal value: ");
scanf("%d",&a);
binary(a);
}
Since it checks whether n/2 == 0 before calling binary() it never prints the intial 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With