Q6. Write a C program to convert a decimal number into a binary number system.

I am sure we all know about number system, still I would like to explain about binary and decimal number system.

Binary number : It is base 2 number system which uses the digits from 0 and 1.

Decimal number : It is base 10 number system which uses the digits from 0 to 9

Method 1:  Stored binary conversion in an array and print it.

#include<stdio.h>

int main()

{

    long int decimal_num, remainder, quotient;

    int binary_num[64], i = 1, j ;

    printf(“Enter any decimal number:\n”);

    scanf(“%ld”,&decimal_num);

    quotient = decimal_num;

    while(quotient!=0)

    {

         binary_num[i++]= quotient % 2;

         quotient = quotient / 2;

    }

    /* Printing binary number equivqlent to given decimal number */

    for(j = i -1; j> 0; j–)

         printf(“%d”,binary_num[j]);

    return 0;

}

Method 2:  You may ask to convert a decimal number into a binary number using function recursion.

#include<stdio.h>

void generate_bits(long int num)

{

 int binary_num;

if(num)

 {

binary_num = num % 2;

generate_bits(num >>= 1);

printf(“%d”, binary_num);

}

}

int main()

{

long int decimal_num;

printf(“Enter any decimal number:\n”);

scanf(“%ld”, &decimal_num);

generate_bits(decimal_num);

return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.