program to print all decimal numbers from 0 to a given number in binary format

advertisements

I'm new to C. I was writing a program to print all the decimal numbers from 0 to a given number(as provided by the user) but my output is not what I had expected. I don't understand what mistake is there in the program I've written....

#include <stdio.h>
int main()
{
    int x,n;
    printf("Enter any number\n");
    scanf("%d",&x);
    n=x;
    printf("numbers in binary format\n");
    while(n!=0)
    {
        int num[8]={0,0,0,0,0,0,0,0};
        int y[8]={0,0,0,0,0,0,0,0};
        int i=7;
        while(x!=0)
        {
            y[i]=x%2;
            x=x/2;
            i=i-1;
        }
        while(i!=8)
        {
            printf("%d",y[i]);
            i=i+1;
        }
        printf("\n");
        n=n-1;
    }
}


The problem is with your first loop

    while(x!=0)
    {
        y[i]=x%2;
        x=x/2;
        i=i-1;
    }

When this loop finishes, your i will not be 0 in most cases, and your second while loop is based on this assumption.

just put a

i = 0;

after your first loop. it should work.