Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A school has n lockers and n students. All lockers are closed on the first day o

ID: 3642263 • 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.

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote