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:
#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
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.