Q:

Write C Program to convert decimal number to binary using function

0

Write C Program to convert decimal number to binary using function

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used Code::blocks 12 compiler for debugging purpose. But you can use any C programming language compiler as per your availability.

#include <stdio.h>
#include <math.h>
 
//Function declaration
long long convertDecimalToBinary(int n);
 
int main()
{
    int n;
    printf("Enter a decimal number: ");
    // Inputting numbers from user
    scanf("%d", &n);
    printf("%d in decimal = %lld in binary", n, convertDecimalToBinary(n));
    return 0;
}
 
long long convertDecimalToBinary(int n)
{
    long long binaryNumber = 0;
    int remainder, i = 1, step = 1;
 
    while (n!=0)
    {
        remainder = n%2;
        //Printing decimal number to binary
        printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}

Result:

Enter a decimal number: 5

Step 1: 5/2, Remainder = 1, Quotient = 2

Step 2: 2/2, Remainder = 0, Quotient = 1

Step 3: 1/2, Remainder = 1, Quotient = 0

5 in decimal = 101 in binary

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write C program to print all strong numbers betwee... >>
<< Write C Program to convert binary number to decima...