There are a number of reasons for your code not working, but one of the main reasons is here:
Code:
// if locker[j] is closed, we open it,
// if locker[j] is already open we leave it that way ...
if (locker[j]==CLOSE) locker[j]=OPEN;
// ... either way when we get to this line locker[j] is
// always open so we close it.
if (locker[j]==OPEN) locker[j]=CLOSE;}
The result is that we always end up with all the lockers closed.
Here is a corrected C version of Sebastiani's code:
Code:
#define OPEN 1
#define CLOSED 0
#define N_LOCKERS 1000
int main(void)
{
int lockers[N_LOCKERS] = { CLOSED };
int index, inc;
int opened = 0, closed = 0;
for(inc = 2; inc <= N_LOCKERS; ++inc) {
for(index = inc - 1; index < N_LOCKERS; index += inc) {
if (lockers[index] == OPEN)
lockers[index] = CLOSED;
else
lockers[index] = OPEN;
}
}
for(index = 0; index < N_LOCKERS; ++index) {
if(lockers[index] == OPEN)
++opened;
else
++closed;
}
printf("There are %d lockers open and %d closed.\n", opened, closed);
return 0;
}
HTH,