Convertin to binary.

I need to write a program that lists all the possible binary combinations {0,1} depending on the number of rows entered by the user. For example if user enters 3, program should print:

(order does not matter)

000
001
010
011
100
101
110
111

Can someone help be with my code!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void convertToBinary(int binary[20], int number){
    int  i=0,j=0;
    int decimal;
    int num = pow(2,number)-1; //The mathematical approac here is to start with a number that is 2^(number) which is the variable 
    //entered by the user, -1 : And then to find all the binary digits corresponding to that number specifically.
    decimal = num;

    while(num > 0){

        decimal = num;
            //Analysing if decimal %2 = 0 or 1 and storing it in an array.
            while(decimal > 0)
            {
                binary[i]= decimal%2;
                i++;
                decimal = decimal/2;
            }

            for(j=number-1;j>=0;j--)
            {
                printf("%d ",binary[j]);
            }
            printf ("\n");

        num--; //Decreasing num to analyze the next number and it's binary digits.

        i=0; //reset counter.

    }

for(i=0;i<number;i++)
    printf("0 ");

}

int main(){
    int N;
    int binary[20];

    printf("Enter a positive integer N: ");
        scanf("%d",&N);

int i=0;
 for (i=0; i< 20; i++)
    {
        binary[i]=0;
    }


        convertToBinary(binary,N);

return 12;
}



Edit: I solved the problem, all I had to do was reset the values of the array to 0 in as the last step in the while loop. Why does that make it work? Can some one explaine
Last edited on
What problem are you facing exactly? Please mention your problem along with the post. You cannot expect someone to just go through your code, find the bug and tell the solution.
Topic archived. No new replies allowed.