Magnum
Magnum

Reputation: 83

Decimal to binary conversion code giving some unusual data

Here is my code for the decimal to binary conversion program:

#include <stdio.h>
#include <stdlib.h>


void main()
{
    int q,r,bn[20],i=0,n;

    printf("enter the decimal integer:");
    scanf("%d",&n);

    while (q>0)
    {   
        q=n/2;
        r=n%2;
        bn[i]=0;
        bn[i]=r;
        n=q;
        i=i+1;
    }
    while(i>=0)
    {
        printf("%d ",bn[i]);
        i=i-1;
    }
}

Now the output is something like this: enter the decimal integer:2 1628731552 1 0 now i don't understand where this number 1628731552 came from ??

Any Help !!

Upvotes: 0

Views: 49

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

Your code invokes Undefined Behavior because of two reasons.

  1. q isn't initialized when the execution of the program reaches

    while(q>0)
    
  2. Secondly, you need to increment i when it is above 0:

    if(q>0)
        i=i+1;
    

    Otherwise, when you input 2, i will be 2 when the first while loop exits and your last printf will access a[2](which is uninitialized) in the first iteration of the last while loop.

    Alternatively, you can use i-- or i=i-1; between the two loops to solve this issue as well.

Upvotes: 1

user586399
user586399

Reputation:

#include <stdio.h>
#include <stdlib.h>


void main()
{
    int q,r,bn[20],i=0,n;

    printf("enter the decimal integer:");
    scanf("%d",&n);

    while (n>0) //fix
    {   
        q=n/2;
        r=n%2;
        //bn[i]=0;
        bn[i]=r;
        n=q;
        i=i+1;
    }
    i--;//go to last idx
    while(i>=0)
    {
        printf("%d",bn[i]);
        i=i-1;
    }
    printf("\n"); // end
}

Upvotes: 0

Related Questions