Sneaker's Stub - The Grey Stuff!

Converting Decimal To Binary Using C language

**NOTE: The following code for “Converting Decimal To Binary Using C language” has been written and performed on Ubuntu OS, To run the following code in Windows on Turbo C, You need to add #include<conio.h> as one of the header files and getch() at the end of the code before main() closing brace “}”.

#include<stdio.h>
void main(){
int b,n,m[50],count=0,i=0,k;
printf("Enter a Number: ");
scanf("%d",&b);
while(b!=0){
n=b%2;
b/=2;
m[i]=n;
count+=1;
i++;
}
for(k=count-1;k>=0;k--){
printf("%d",m[k]);
}
}

Explanation for the Above Program:

  • Input a number from the user ------> b
  • Run the while loop with the condition b is ┬ánot equal to Zero -----------> b!=0
  • Divide the input variable by 2 to get the remainder and store it in another variable---------> n = b % 2
  • Divide the input value again to get the quotient and store it in the input variable itself -------> b/=2
  • Store the Remainder in an array variable and increment the index i by 1---------->m[i]=n
  • "count" variable above keep tracks of the number of times the loop runs.---------->count+=1
  • Print the array values using for loop with "k" as a looping variable which runs from backwards "count" to 0. ------------>for(k=count;k>=0;k--)
  • Print the array index values.

Output:

converting decimal to binary output

 



Leave a Reply