Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Converting Positive Integers to Binary Representation We would like to write a C

ID: 639669 • Letter: C

Question

Converting Positive Integers to Binary Representation
We would like to write a C program to convert a decimal representation of a positive

integer to binary representation. The flow chart on the next page describes how the algorithm works.

This algorithm will print out the binary equivalent of the input, unfortunately, it prints it out in reverse order. Maybe later we can fix this issue.

Use appropriate loop types to construct the algorithm. HINT: use while or do-while loop Make sure your algorithm prints out 0 for an input of 0.

Test case:

Note: * the correct binary is actually a reverse order of what our program gives. For example, binary representation of 181 is 10110101. See section 2.10 in the textbook for Binary and Decimal.

Explanation / Answer

#include<stdio.h>

int main(){

    long int decimalNumber,remainder,quotient;

    int binaryNumber[100],i=1,j;

    printf("Enter any decimal number: ");

    scanf("%ld",&decimalNumber);

    quotient = decimalNumber;

    while(quotient!=0){

         binaryNumber[i++]= quotient % 2;

         quotient = quotient / 2;

    }

    printf("Equivalent binary value of decimal number %d: ",decimalNumber);

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

         printf("%d",binaryNumber[j]);

    return 0;

}

Sample output:

Enter any decimal number: 50

Equivalent binary value of decimal number 50: 110010