Open In App

Bus Reservation System in C

Last Updated : 22 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Bus Reservation System is a tool that allows users to book tickets for their journey in advance. It offers multiple features to provide a hassle-free experience to a traveler. This article aims at building a rudimentary Bus Reservation System.

Components of the Bus Reservation System

  • Login System: Users can access the system by entering their username and password. The program provides a collection of preconfigured users and their credentials.
  • Ticket Purchase: Logged-in individuals may reserve tickets for available buses by entering the bus number, their name, and age. The program allocates a seat number and decreases the number of available seats on the selected bus.
  • Cancel Tickets: By entering their name, users can cancel their tickets. The program expands the number of available seats while removing the passenger entry.
  • Checking Bus Status: Users may check the status of the bus they are currently scheduled to ride on. The program displays information such as the bus number, origin and destination, total number of seats, available seats, and fare.

The program employs frameworks to organize data for buses, passengers, and users. It also has menus for both the main menu (login) and the user menu (booking, canceling, and checking status).

Note: This is a simple example; in a real-world scenario, you would want to improve security, error handling, and data durability, potentially by storing user and booking information in file storage or a database.

Implementation of Bus Reservation System

C




// C Program to implement Bus Reservation System
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// Define a structure to store bus information
struct Bus {
    int busNumber;
    char source[50];
    char destination[50];
    int totalSeats;
    int availableSeats;
    float fare;
};
  
// Define a structure to store passenger information
struct Passenger {
    char name[50];
    int age;
    int seatNumber;
    int busNumber;
};
  
// Define a structure to store user login information
struct User {
    char username[50];
    char password[50];
};
  
// Function to display the main menu
void displayMainMenu()
{
    printf("\n=== Bus Reservation System ===\n");
    printf("1. Login\n");
    printf("2. Exit\n");
    printf("Enter your choice: ");
}
  
// Function to display the user menu
void displayUserMenu()
{
    printf("\n=== User Menu ===\n");
    printf("1. Book a Ticket\n");
    printf("2. Cancel a Ticket\n");
    printf("3. Check Bus Status\n");
    printf("4. Logout\n");
    printf("Enter your choice: ");
}
  
// Function to perform user login
int loginUser(struct User users[], int numUsers,
              char username[], char password[])
{
    for (int i = 0; i < numUsers; i++) {
        if (strcmp(users[i].username, username) == 0
            && strcmp(users[i].password, password) == 0) {
            return i; // Return the index of the logged-in
                      // user
        }
    }
    return -1; // Return -1 if login fails
}
  
// Function to book a ticket
void bookTicket(struct Bus buses[], int numBuses,
                struct Passenger passengers[],
                int* numPassengers, int userId)
{
    printf("\nEnter Bus Number: ");
    int busNumber;
    scanf("%d", &busNumber);
  
    // Find the bus with the given busNumber
    int busIndex = -1;
    for (int i = 0; i < numBuses; i++) {
        if (buses[i].busNumber == busNumber) {
            busIndex = i;
            break;
        }
    }
  
    if (busIndex == -1) {
        printf("Bus with Bus Number %d not found.\n",
               busNumber);
    }
    else if (buses[busIndex].availableSeats == 0) {
        printf("Sorry, the bus is fully booked.\n");
    }
    else {
        printf("Enter Passenger Name: ");
        scanf("%s", passengers[*numPassengers].name);
  
        printf("Enter Passenger Age: ");
        scanf("%d", &passengers[*numPassengers].age);
  
        // Assign a seat number to the passenger
        passengers[*numPassengers].seatNumber
            = buses[busIndex].totalSeats
              - buses[busIndex].availableSeats + 1;
  
        // Update the passenger's bus number
        passengers[*numPassengers].busNumber = busNumber;
  
        // Update available seats
        buses[busIndex].availableSeats--;
  
        printf("Ticket booked successfully!\n");
        (*numPassengers)++;
    }
}
  
// Function to cancel a ticket
void cancelTicket(struct Bus buses[], int numBuses,
                  struct Passenger passengers[],
                  int* numPassengers, int userId)
{
    printf("\nEnter Passenger Name: ");
    char name[50];
    scanf("%s", name);
  
    int found = 0;
    for (int i = 0; i < *numPassengers; i++) {
        if (strcmp(passengers[i].name, name) == 0
            && passengers[i].busNumber
                   == buses[userId].busNumber) {
            // Increase available seats
            int busIndex = -1;
            for (int j = 0; j < numBuses; j++) {
                if (buses[j].busNumber
                    == passengers[i].busNumber) {
                    busIndex = j;
                    break;
                }
            }
            buses[busIndex].availableSeats++;
  
            // Remove the passenger entry
            for (int j = i; j < (*numPassengers) - 1; j++) {
                passengers[j] = passengers[j + 1];
            }
            (*numPassengers)--;
            found = 1;
            printf("Ticket canceled successfully!\n");
            break;
        }
    }
    if (!found) {
        printf("Passenger with name %s not found on this "
               "bus.\n",
               name);
    }
}
  
// Function to check bus status
void checkBusStatus(struct Bus buses[], int numBuses,
                    int userId)
{
    printf("\nBus Number: %d\n", buses[userId].busNumber);
    printf("Source: %s\n", buses[userId].source);
    printf("Destination: %s\n", buses[userId].destination);
    printf("Total Seats: %d\n", buses[userId].totalSeats);
    printf("Available Seats: %d\n",
           buses[userId].availableSeats);
    printf("Fare: %.2f\n", buses[userId].fare);
}
  
int main()
{
    // Initialize user data
    struct User users[5] = {
        { "user1", "password1" }, { "user2", "password2" },
        { "user3", "password3" }, { "user4", "password4" },
        { "user5", "password5" },
    };
    int numUsers = 5;
  
    // Initialize bus data
    struct Bus buses[3] = {
        { 101, "City A", "City B", 50, 50, 25.0 },
        { 102, "City C", "City D", 40, 40, 20.0 },
        { 103, "City E", "City F", 30, 30, 15.0 },
    };
    int numBuses = 3;
  
    struct Passenger
        passengers[500]; // Array to store passenger
                         // information
    int numPassengers = 0; // Number of passengers
  
    int loggedInUserId = -1; // Index of the logged-in user
  
    while (1) {
        if (loggedInUserId == -1) {
            displayMainMenu();
            int choice;
            scanf("%d", &choice);
  
            if (choice == 1) {
                char username[50];
                char password[50];
  
                printf("Enter Username: ");
                scanf("%s", username);
                printf("Enter Password: ");
                scanf("%s", password);
  
                loggedInUserId = loginUser(
                    users, numUsers, username, password);
                if (loggedInUserId == -1) {
                    printf("Login failed. Please check "
                           "your username and password.\n");
                }
                else {
                    printf(
                        "Login successful. Welcome, %s!\n",
                        username);
                }
            }
            else if (choice == 2) {
                printf("Exiting the program.\n");
                break;
            }
            else {
                printf(
                    "Invalid choice. Please try again.\n");
            }
        }
        else {
            displayUserMenu();
            int userChoice;
            scanf("%d", &userChoice);
  
            switch (userChoice) {
            case 1:
                bookTicket(buses, numBuses, passengers,
                           &numPassengers, loggedInUserId);
                break;
            case 2:
                cancelTicket(buses, numBuses, passengers,
                             &numPassengers,
                             loggedInUserId);
                break;
            case 3:
                checkBusStatus(buses, numBuses,
                               loggedInUserId);
                break;
            case 4:
                printf("Logging out.\n");
                loggedInUserId = -1;
                break;
            default:
                printf(
                    "Invalid choice. Please try again.\n");
            }
        }
    }
  
    return 0;
}


Output:

Bus Reservation System - output Bus Reservation System - output

Step-by-Step Explanation

1. Initialization of Structures and Variables:

  • The code starts by defining three structures: `struct Bus` to store bus information, `struct Passenger` for passenger details, and `struct User` to store user login information.
  • It also includes necessary libraries and declares functions for displaying menus, user login, booking tickets, canceling tickets, and checking bus status.
  • Three arrays are initialized:
    • `struct User users[5]` stores user login credentials for five users.
    • `struct Bus buses[3]` stores information about three different buses.
    • `struct Passenger passengers[500]` is an array to store passenger details.
    • `numUsers`, `numBuses`, and `numPassengers` are variables to keep track of the number of users, buses, and passengers.
    • `loggedInUserId` is initially set to -1, indicating that no user is logged in.

2. Main Function and Program Loop:

  • The `main` function is the entry point of the program.
  • It initializes the user data, bus data, passenger data, and the `loggedInUserId` variable.
  • The program enters a `while (1)` loop, which serves as the main program loop and runs until the user chooses to exit.

3. Main Menu (displayMainMenu):

  • If no user is logged in (`loggedInUserId == -1`), the program displays the main menu with options to “Login” or “Exit.”

4. User Login (loginUser):

  • If the user selects “Login” (choosing option 1), the program prompts the user to enter their username and password.
  • The `loginUser` function is called, which checks if the provided username and password match any of the predefined users in the `users` array.
  • If a match is found, the `loggedInUserId` is set to the index of the logged-in user, and a welcome message is displayed.
  • If no match is found, a login failed message is shown, and the user can try again or choose to exit.

5. User Menu (displayUserMenu):

  • If a user is logged in (`loggedInUserId >= 0`), the program displays the user menu with options to “Book a Ticket,” “Cancel a Ticket,” “Check Bus Status,” or “Logout.”

6. Booking a Ticket (bookTicket):

  • If the user selects “Book a Ticket” (option 1 from the user menu), the program asks for the bus number they want to book a ticket for.
  • It then searches for the selected bus in the `buses` array and checks if there are available seats.
  • If there are available seats, the program prompts the user to enter their name and age. It assigns a seat number, records the passenger’s bus number, and updates the available seats.
  • A success message is displayed, and the number of passengers (`numPassengers`) is incremented.

7. Canceling a Ticket (cancelTicket):

  • If the user selects “Cancel a Ticket” (option 2 from the user menu), the program asks for the passenger’s name.
  • It then searches for the passenger in the `passengers` array, ensuring that the passenger is on the bus of the currently logged-in user. If found, the ticket is canceled, the available seats are increased, and the passenger entry is removed.

8. Checking Bus Status (checkBusStatus):

  • If the user selects “Check Bus Status” (option 3 from the user menu), the program displays information about the bus the user is currently booked on. This includes the bus number, source, destination, total seats, available seats, and fare.

9. Logging Out:

  • If the user selects “Logout” (option 4 from the user menu), they are logged out, and `loggedInUserId` is set back to -1.

10. Exiting the Program:

  • If the user selects “Exit” from the main menu (option 2), the program exits the `while (1)` loop and ends.

This code simulates a basic bus reservation system, allowing users to log in, book and cancel tickets, check bus status, and log out. Note that this code is a simplified example and lacks error handling and data persistence features commonly found in production systems.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads