Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have a question similar to the locker puzzle, but I need to take input from user to determine the amount of lockers and students

I have a question similar to the locker puzzle, but I need to take input from user to determine the amount of lockers and students (both can go up to 100).

I am not sure if my code is doing what is supposed to regarding the loops. But I is not taking my input for lockers and student, when it prints it always go up to 100. How can I fix it?

This is what I got:

#include #include #include

#define MAX_LOCKERS 100 #define MAX_STUDENTS 100 #define FLUSH stdin=freopen(NULL,"r",stdin)

char loc[MAX_LOCKERS] = {0}; char s[MAX_STUDENTS] = {0};

int main() {

int i, j, locker, std; bool lockers[MAX_LOCKERS + 1] = {false};

do { printf("Input number of lockers (1-100): "); fgets(loc, MAX_LOCKERS, stdin); FLUSH; locker = strtol(loc, NULL, 10);

if (locker < 1 || locker > MAX_LOCKERS) { printf("Incorrect input. Please try again! "); } } while (locker < 1 || locker > MAX_LOCKERS);

do { printf("Input number of students (1-100): "); fgets(s, MAX_STUDENTS, stdin); FLUSH; std = strtol(s, NULL, 10);

if (std < 1 || std > MAX_STUDENTS) { printf("Incorrect input. Please try again! "); } } while (std < 1 || std > MAX_STUDENTS);

//only for the first student, it will open all lockers for (i = 1; i <= MAX_LOCKERS; i++) { lockers[i] = true; }

//for the even number of students (second student and on) ---- from last locker to first if (std % 2) { for (i = MAX_LOCKERS; i > 0; i--) { for (j = 1; j <= MAX_STUDENTS; j += i) { lockers[i] = !lockers[i]; } } }

//for the odd number of students (third student and on) if (std % 2 == false) { for (i = 0; i <= MAX_LOCKERS; i++) { for (j = 1; j <= MAX_STUDENTS; j += i) { lockers[i] = !lockers[i]; } } }

//to print the lockers that are open at the end printf("The school has %d lockers and %d students. Open lockers: ", locker, std); for (i = 1; i <= MAX_LOCKERS; i++) { if (lockers[i]) { printf("%d, ", i); } } return 0; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

What Is A Database And How Do I Use It

Authors: Matt Anniss

1st Edition

1622750799, 978-1622750795

More Books

Students also viewed these Databases questions

Question

=+j Describe an effective crisis management program.

Answered: 1 week ago