C Program to Convert Decimal to Binary



This is a simple easy C program which convert decimal into binary number. First it divide the decimal number by 2 and store remainder in an array and then display the array in reverse, This is how it convert into binary number, This whole program is in 'for loop' thus we can also find binary number between specific range.


Also read: C program to convert Binary into Decimal number


Program:

#include <stdio.h>
#include <conio.h>

long decimalToBinary(long n);

/*C Program to Convert Decimal to Binary by SlashMyCode.com*/

int main() 

{
    long decimal;
    int n,m,i;

    printf("from: ");
    scanf("%d",&n);

    printf("  to: ");
    scanf("%d",&m);

    printf("===============\n");

    for(i=n;i<=m;i++)
         {
            decimal=i;
            printf("%ld \n", decimalToBinary(decimal));
         }
   printf("===============\n");
 getch();
    return 0;
}



/* Function to convert a decimal number into binary number */
long decimalToBinary(long n)
  {
    int remainder;
    long binary = 0, i = 1;

           while(n != 0)
             {
             remainder = n%2;
             n = n/2;
             binary= binary + (remainder*i);
             i = i*10;
             }
    return binary;
/*C Program to Convert Decimal to Binary by SlashMyCode.com*/
  }



Output:




No comments:

Post a Comment

Feel free to ask us any question regarding this post