Creating a simple airplane reservation program program will not start over

Viewed 38

This is the code that I have. Currently the code prints out all the seats at once. I need it to print one seat and then restart to the user prompt. it can not assign the same seat and should show first class full when there are no more seats.

int main(int argc, char** argv) {

int firstClass[] = {1, 2, 3, 4}; //first class array
int firstLen = 4; // first class length
int userInput;
int i;

//user prompt
printf("Please type 1 for First Class\n");
printf("Please type 2 for Economy\n");
printf("Please type 0 to Quit\n");
printf("\n");
scanf("%d", &userInput); // scanning for user input

 
if(userInput = 1){
    for(i = 0; i < 4; i++){
        if(i < firstLen){
            printf("Class: First     Seat Number: %d\n", firstClass[i]);
            
        }
        else{
            printf("First Class Full. Next flight is tomorrow.");
        }
        
    }
}

}

1 Answers

You can track which seats are taken with a variable. Each time a user selects 1 print out the seat number for that index, and then increment the index.

You'll then wrap this in a loop (for or while) and only exit the loop when the user enters 0. Make sure you define the variable used to track the current index outside of the loop.

Something like this:

int main(void)  
{
    const int first_class[] = {1, 2, 3, 4};
    const size_t first_class_size = sizeof(first_class) / sizeof(first_class[0]); 

    size_t first_class_index = 0;
    int user_input = 0;

    do
    {
        print_menu();
        scanf("%d", &user_input);

        if (user_input == 1) 
        {
            if (first_class_index < first_class_size) 
            {
                printf("Here is your ticket information:\n");
                printf("Seat Number: %d, Class: First\n\n", first_class[first_class_index++]);
                continue;
            }
            printf("No first class seats are available.\n\n");
        }
    } while(user_input != 0); 
}
Related