#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
#define MAX_TITLE_LENGTH 50
#define MAX_AUTHOR_LENGTH 50
typedef enum BookCategory {
FICTION,
NONFICTION,
SCIENCE,
SPORTS,
CATEGORY_COUNT
} BookCategory;
typedef struct Book {
char title[MAX_TITLE_LENGTH];
char author[MAX_AUTHOR_LENGTH];
BookCategory category;
} Book;
#define MENU_OPTIONS 4
void addBook(Book **books, int *count);
void deleteBook(Book **books, int *count);
void printBooks(Book **books, int count);
void exitProgram(Book **books, int *count);
void (*menuFunctions[MENU_OPTIONS])(Book **, int *) = {
addBook,
deleteBook,
printBooks,
exitProgram
};
int main() {
Book *books[MAX_BOOKS] = {0};
int bookCount = 0;
int choice;
while (1) {
printf("\nMenu:\n");
printf("1. Add Book\n");
printf("2. Delete Book\n");
printf("3. Print Books\n");
printf("4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
if (choice < 1 || choice > MENU_OPTIONS) {
printf("Invalid choice. Please try again.\n");
continue;
}
menuFunctions[choice - 1](&books[0], &bookCount);
if (choice == MENU_OPTIONS) break;
}
return 0;
}
void addBook(Book **books, int *count) {
if (*count >= MAX_BOOKS) {
printf("Maximum number of books reached.\n");
return;
}
Book *newBook = (Book *)malloc(sizeof(Book));
if (!newBook) {
printf("Memory allocation failed.\n");
return;
}
printf("Enter book title: ");
scanf("%49s", newBook->title);
printf("Enter author name: ");
scanf("%49s", newBook->author);
printf("Enter category (0 for Fiction, 1 for Nonfiction, 2 for Science, 3 for Sports): ");
scanf("%u", (unsigned int *)&newBook->category);
books[*count] = newBook;
(*count)++;
printf("Book added successfully.\n");
}
void deleteBook(Book **books, int *count) {
int index;
printf("Enter index of book to delete: ");
scanf("%d", &index);
if (index < 0 || index >= *count) {
printf("Invalid index.\n");
return;
}
free(books[index]);
for (int i = index; i < *count - 1; i++) {
books[i] = books[i + 1];
}
books[*count - 1] = NULL;
(*count)--;
printf("Book deleted successfully.\n");
}
void printBooks(Book **books, int count) {
if (count == 0) {
printf("No books to display.\n");
return;
}
printf("Books:\n");
for (int i = 0; i < count; i++) {
printf("%d: %s by %s, Category: %d\n", i, books[i]->title, books[i]->author, books[i]->category);
}
}
void exitProgram(Book **books, int *count) {
for (int i = 0; i < *count; i++) {
free(books[i]);
}
printf("Exiting program...\n");
}