Summary: This C program manages a small collection of books. It stores and displays book details, and filters books published after 2015 with more than 10 available copies.
#include <stdio.h>
#include <string.h>
// Define the Book structure
struct Book {
char title[100];
char author[50];
char isbn[20];
float price;
int yearPublished;
int copiesAvailable;
};
// Function to display a single book's details
void displayBook(struct Book b) {
printf("\nTitle:\t\t\t%s\n", b.title);
printf("Author:\t\t\t%s\n", b.author);
printf("ISBN:\t\t\t%s\n", b.isbn);
printf("Price:\t\t\t₹%.2f\n", b.price);
printf("Year Published:\t\t%d\n", b.yearPublished);
printf("Copies Available:\t%d\n", b.copiesAvailable);
}
int main() {
// Declare and initialize the array of books (5 books)
struct Book books[5] = {
{"The C Programming Language", "Kernighan & Ritchie", "9780131103627", 450.0, 1988, 5},
{"Let Us C", "Yashavant Kanetkar", "9788176566217", 380.0, 2017, 15},
{"Clean Code", "Robert C. Martin", "9780132350884", 720.0, 2016, 12},
{"Python Crash Course", "Eric Matthes", "9781593279288", 650.0, 2019, 20},
{"Algorithms Unlocked", "Thomas H. Cormen", "9780262518802", 800.0, 2013, 8}
};
printf("All Book Details:\n");
for (int i = 0; i < 5; i++) {
displayBook(books[i]);
}
printf("\nBooks published after 2015 and with more than 10 copies:\n");
int found = 0;
for (int i = 0; i < 5; i++) {
if (books[i].yearPublished > 2015 && books[i].copiesAvailable > 10) {
displayBook(books[i]);
found = 1;
}
}
if (!found) {
printf("No books found matching the criteria.\n");
}
return 0;
}
Structures:
The program uses a struct Book
to define a custom data type that groups book-related attributes together (title, author, ISBN, price, year, and number of copies).
Array of Structures:
Books are stored in an array of struct Book
. This allows efficient iteration and processing of each book using loops.
Function Usage:
The function displayBook()
improves code modularity by encapsulating the logic for printing book details. This avoids repetition and enhances readability.
Conditional Filtering:
A for
loop is used with an if
condition to filter books based on two criteria: published after 2015 and more than 10 copies available. This demonstrates combined conditional logic using the &&
(AND) operator.
Control Variable:
A found
flag variable is used to determine whether any matching books exist, allowing the program to handle and print a message if none are found.
Formatted Output:
The program uses \t
and \n
for clean and aligned terminal output, and %.2f
to format float values like price.