A school has n lockers and n students. All lockers are closed on the first day o
ID: 3642273 • Letter: A
Question
A school has n lockers and n students. All lockers are closed on the first day of school.As the students enter, the first student (S1) opens every locker beginning with
locker one (L1).
Then, the second student (S2), beginning with the second locker (L2), closes
every other locker.
Student three (S3), beginning with the third locker (L3), changes every third
locker (closes the locker if it is opened and opens the locker if it is closed).
Student four (S4), beginning with the fourth locker (L4), changes every fourth
locker.
Student five (S5), beginning with locker five (L5), changes every fifth locker.
This continues until Student n (Sn), changes just the last/nth locker.
When finished opening/closing lockers, output which lockers are open. For this
program, you MUST use an array to represent the student lockers, and you MUST
prompt for n.
Use two nested for-loops to manage both the student number and every nth
locker. That is, the outer for-loop steps through each student 1 to n. The inner
for-loop steps through every nth locker.
Let the array be used to track the total times a locker changes (either opened or
closed). If the final number of times is even, the locker is closed. If the final
number of times is odd, the locker is open.
Explanation / Answer
% lockers.m
% simulate the locker problem...
%
%
% prompt for input
numlockers = input('Enter number of lockers: ');
% initialize locker array to zeros (lockers are closed)
lockers = zeros(1,numlockers);
% run the simulation
for student = 1:numlockers
% loop through all of the students
for i = student:student:numlockers
% loop through lockers for each student
lockers(i) = lockers(i) + 1;
% toggle each locker visited by the student
end
end
% display results
for j = 1:numlockers
% loop through each locker
if (mod(lockers(j),2) == 0) % even -- locker is closed
fprintf('locker #%d is closed ', j);
else % odd - locker is open
fprintf('locker #%d is open ', j);
end
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.