Question
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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started