Say for arguement sake there were 25 students and 25 lockers.
You could use a for loop to load the first 25 elements of array l [100]={0}
with 1 (all elements have been initialized to 0)
When printed you would get 1111111111111111111111111 (ie 25 1's)
This would represent the first student opening all doors
Then you could write a for loop that would change every second element to 0.
You would get 1010101010101010101010101 even doors 2,4,6 etc are now closed (0)by the second student. Then you could use a for loop to check the third door (and every 3rd door there after) and if open as in this case (1)change element 3,6,9,12 etc to '0' or '1' as the case may require. The loop might look something like this:
- for(int i=2;i<lockers;i+=3)//check every 3rd locker and change 0/1 status
-
if(i>0 && l[i]==1)l[i]=0;
-
else if (i>0 && l[i]==0)l[i]=1;
The print out would maybe look like this:-1000111000111000111000111
Now write a similar loop for the 4th door and every 4th door there after and so on. By printing out each row you can easily check for accuracy.
You could then play with reducing code repetition. The fact that 0 and 1 represent closed and open respectfully might allow boolian controlled loops.
I can`t help thinking that there is a simple and direct mathematical solution which would cut out all this loop code but can`t see it.