backstory (if interested):
Recently, I have learned to write numbers in binary. So, I wanted to see if I could write every single possibility for 32-bits. So, I started, and after having successfully finished a mere 10-bits, I looked up the total amount of solutions for 32-bits. Turns out it is way way way more than I thought (well over 4 billion). So I thought a fun challenge would be to write a custom program (in C) that would calculate every single possible answer for 32-bits.
For this, I used an array with 32 items in it. Then, I check if the 32nd value is equal to 0. If it is, then I simply change it to be 1. If it is 1, I change it to be 0, and then change every item after that (equal to 1) back to zero, until I hit a 0. Here is my code :
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
int bits[32] = {1, 0};
for (int i=0;i<3000;i++)
{
for (int j=0;i<32;i++)
{
if (bits[32] == 0)
{
bits[32] = 1;
}
else if (bits[32] == 1)
{
int k = 0;
for (k = 0;k<32;k++)
{
int position = 32-k;
while(bits[position] != 0)
{
bits[position] = 0;
}
bits[position+1] = 1;
}
}
}
for (int i=0;i<32;i++)
{
printf("%d", bits[i]);
}
printf("\n");
}
getchar();
return 0;
}
And then I hit a major roadblock. It didn't work at all (just plug into any IDE, run it and you will see it for yourself). It seemed perfectly logical in my head, but apparently it doesn't work like that, and I will admit I am completely lost. Does anyone know (without feeding me the whole code, I still want to do it myself) why this doesn't work, and how to fix it ? Thank you very much.
bits[32]is out of range. You can indexbits[0]thrubits[31]. Similarlyint position = 32-k;will be off-by-one inbits[position].(int j=0;i<32;i++)isn't this supposed to bej?. A good idea is to have different name forforindicies. The second nestedforalso usesiand i do not think it is intended.