The Wayback Machine - https://web.archive.org/web/20240822004342/https://www.geeksforgeeks.org/bus-reservation-system-in-c/
Open In App

Bus Reservation System in C

Last Updated : 22 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

Segmentation Fault (SIGSEGV) vs Bus Error (SIGBUS)
Segmentation fault(SIGSEGV) and Bus error(SIGBUS) are signals generated when serious program error is detected by the operating system and there is no way the program could continue to execute because of these errors.1) Segmentation Fault (also known as SIGSEGV and is usually signal 11) occur when the program tries to write/read outside the memory
3 min read
Bank account system in C using File handling
This article focuses on how to create a bank account system using C language and File handling in C. Approach:Let's discuss the approach in detail, covering all the functions and their explanation in detail- Create a Menu in the main function and create different functions for the Menu, which will be called using switch case statements. There are f
12 min read
Getting System and Process Information Using C Programming and Shell in Linux
Whenever you start a new process in Linux it creates a file in /proc/ folder with the same name as that of the process id of the process. In that folder, there is a file named "status" which has all the details of the process. We can get those Process Information Through shell as follows: cat /proc/1/status As can be seen, it displays most of the i
2 min read
How does Volatile qualifier of C works in Computing System
Prerequisite: Computing systems, Processing unit Processing Unit:Processing units also have some small memory called registers.The interface between the processor (processing unit) and memory should work on the same speed for better performance of the system.Memory: In memory, there are two types, SRAM and DRAM. SRAM is costly but fast and DRAM is
3 min read
Difference between system() and execl() call
A system() call is a way for the programs to interact with the operating system. It is used to execute a command within a process. The system call provides the services of the operating system to the user programs via Application Program Interface (API). It provides an interface between a process and an operating system and it does not replace the
4 min read
Department Store Management System(DSMS) using C++
A Department Store Management System (DSMS) in C++ is a software tool used to manage the inventory and sales of items in a department store. In this article, we will be discussing the implementation of a DSMS on a command-line user interface using C++. The system allows various features to admin such as add, view, update, and delete items in the st
8 min read
Telecom Billing System in C
In this article, we are going to create a basic Telecom Billing System using the C programming language. This system allows users to perform operations such as adding new customer records, viewing the list of records, modifying existing records, viewing payment details, searching for specific records, and deleting records. What is a Telecom Billing
9 min read
Hospital Management System in C
A Hospital Management System is software that facilitates its users some basic operations that take place in a typical hospital. This Hospital Management System in C language is a project for Hospitals having the following functionalities: Printing Hospital DataPrint Patients DataSort by Bed PriceSort by Available BedsSort by NameSort by Rating and
11 min read
Online Voting System in C
Voting in elections is one of the most fundamental organs of any Democracy and in the modern world, voting is done through digital machines. In this article, we will try to write a simple Online Voting System using C programming language. Features of Online Voting System in CThe online voting system offers the following functions: Taking a Vote fro
5 min read
Input-output system calls in C | Create, Open, Close, Read, Write
System calls are the calls that a program makes to the system kernel to provide the services to which the program does not have direct access. For example, providing access to input and output devices such as monitors and keyboards. We can use various functions provided in the C Programming language for input/output system calls such as create, ope
10 min read
system() in C/C++
The system() function is used to invoke an operating system command from a C/C++ program. For example, we can call system("dir") on Windows and system("ls") in a Unix-like environment to list the contents of a directory. It is a standard library function defined in &lt;stdlib.h&gt; header in C and &lt;cstdlib&gt; in C++. SyntaxThe syntax of system(
6 min read
Amazing stuff with system() in C / C++
system() plays a very special role in executing Operating System Commands. By using this library function we can run all those terminal commands that our Operating System allows us to perform, just by using our C program. Now, we will learn a very simple code to fetch the IP Address - to identify each computer using that very internet Protocol to c
2 min read
pipe() System call
Prerequisite : I/O System calls Conceptually, a pipe is a connection between two processes, such that the standard output from one process becomes the standard input of the other process. In UNIX Operating System, Pipes are useful for communication between related processes(inter-process communication). Pipe is one-way communication only i.e we can
4 min read
Simple Personal Diary Management System in C
Keeping a personal diary has been a timeless practice for a lot of individuals to reflect on their thoughts and experiences. In this article, we will look at a simple personal diary management application in C. Prerequisite: Basic C Knowledge, File Handling in C, and Time in C. Features of Diary Management System in C This simple diary management a
3 min read
Number System Conversion in C
Number system conversion is a fundamental concept in computer science and programming. It involves changing the representation of a number from one base to another, such as converting a decimal number to binary or a hexadecimal number to binary. In this article, we will create a console program in the C language to perform various number system con
7 min read
Wait System Call in C
Prerequisite : Fork System callA call to wait() blocks the calling process until one of its child processes exits or a signal is received. After the child process terminates, parent continues its execution after wait system call instruction. Child process may terminate due to any of these:  It calls exit();It returns (an int) from mainIt receives a
4 min read
Grokking Modern System Design Interview Guide
This System Design Interview Guide will provide the latest system design interview questions and equip you with knowledge and techniques needed to design, build, and scale your own robust applications, for professionals as well as newbies.
3 min read
System Design Cheat Sheet
Welcome to the System Design Cheat Sheet. Join us on a journey to master the principles and techniques of designing complex systems and get ready to dive into the world of designing scalable, efficient, and robust systems
3 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Top 50 C Coding Interview Questions and Answers (2024)
C is the most popular programming language developed by Dennis Ritchie at the Bell Laboratories in 1972 to develop the UNIX operating systems. It is a general-purpose and procedural programming language. It is faster than the languages like Java and Python. C is the most used language in top companies such as LinkedIn, Microsoft, Opera, Meta, and N
15+ min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
C Programs: Practicing and solving problems is the best way to learn anything. Here, we have provided 100+ C programming examples in different categories like basic C Programs, Fibonacci series in C, String, Array, Base Conversion, Pattern Printing, Pointers, etc. These C programs are the most asked interview questions from basic to advanced level.
9 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
std::sort() in C++ STL
We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access) It generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. The
6 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
three90RightbarBannerImg