The need:
This program converts a given decimal integer to equivalent binary number.
This program converts a given decimal integer to equivalent binary number.
The code:
--------------------------------------------
#include<stdio.h> main() { int i=0,j,k,l,m; char str1[50],str2[50]; printf("Enter a decimal integer => "); scanf("%d",&k); m=k; //storing k for further use while(k>0){ //while loop for storing remainder if(k%2==0) //of each division by 2 in a string str1[i]='0'; //variable str1 else str1[i]='1'; k/=2; i++; } str1[i]='\0'; l=i; j=i-1; for(i=0;j>=0;i++,j--) str2[j]= str1[i]; printf("The binary equivalent of %d is => ",m); for(j=0;j<l;j++) putchar(str2[j]); getchar(); }--------------------------------------------
The approach:
Here is an alternative method, without using string to store the remainder. It's sort of better way of doing.
ReplyDeleteC program to convert decimal number into binary
good to see this. But your program wont convert decimal numbers which have binary conversion more than 10 binary digits while this program will. I also have further extension of this program using which you can convert up to 2000digit decimal integer. :)
ReplyDeleteI have written this code and it seems to work pretty well
ReplyDelete#include
int main()
{
int n,r=0,sum[100],j;
scanf("%d",&n);
int i=0;
while(n!=0)
{
r=n%2;
sum[i]=r;
n=n/2;
i++;
}
//sum[i+1]="\0";
printf("digits of number in binary is \n");
for(j=i-1;j>=0;j--)
printf("%d",sum[j]);
printf("\n");
return 0;
}
Good. You are doing the same with integer array what I have done with character array. the only difference is, you didn't store the reversed binary value, just printed the reverse.
Delete