Decimal to binary conversion

Report
Question

Please briefly explain why you feel this question should be reported .

Report
Cancel

I am trying to convert a decimal number input from user to its binary value using a function. I saw the solution given on w3resource.com and it all went good except one point i didnt understand. Below is the code :

CODE:
#include<stdio.h>

long toBin(int);

int main()
{
long bno;
int dno;
printf(“\n\n Function : convert decimal to binary :\n”);
printf(“——————————————-\n”);
printf(” Input any decimal number : “);
scanf(“%d”,&dno);
bno = toBin(dno);
printf(“\n The Binary value is : %ld\n\n”,bno);

return 0;
}
long toBin(int dno)
{
long bno=0,remainder,f=1;
while(dno != 0)
{
remainder = dno % 2;
bno = bno + remainder * f;
f = f * 10;
dno = dno / 2;
}
return bno;
}

Now the point im not getting is that in a variable’ int bno’ how is the binary value stored like an array? or is it something else i dont know? i have underlined both the lines which i do not understand. Please clerify this to me…

in progress 0
C++ 2 months 1 Answer 1057 views 0

About learner47

Answer ( 1 )

  1. rg123

    Please briefly explain why you feel this answer should be reported .

    Report
    Cancel

    Check the values of bno, remainder, f, dno. Hope you will get your answer.
    The following code runs using c# (same logic)

    #include<stdio.h>
    long toBin(int);
    int main()
    {
        long bno;
        int dno;
        printf("\n\n Function : convert decimal to binary :\n");
        printf("-------------------------------------------\n");    
        printf(" Input any decimal number : ");
        scanf("%d",&dno);
        bno = toBin(dno);
        printf("\n The Binary value is : %ld\n\n",bno);
    
        return 0;
    }
    long toBin(int dno)
    {
        long bno=0,remainder=0,f=1;
        while(dno != 0)
        {
             printf("\n bno, remainder, f, dno : %ld, %ld, %ld, %d",bno, remainder, f, dno);
             remainder = dno % 2;         
             bno = bno + remainder * f;              
             f = f * 10;
             dno = dno / 2;
        }
        return bno;
    }
    

    Output:

    Function : convert decimal to binary :
    ——————————————-
    Input any decimal number : 7

    bno, remainder, f, dno : 0, 0, 1, 7
    bno, remainder, f, dno : 1, 1, 10, 3
    bno, remainder, f, dno : 11, 1, 100, 1
    The Binary value is : 111

    More: http://www.w3resource.com/c-programming-exercises/function/c-function-exercise-6.php

Leave an answer

Browse

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>