Nested Structure Book Library
C
Hard
2 views
Problem Description
Create book structure (title, author structure (name, country), year, price). Create array of books and implement search function by author name.
Official Solution
#include <stdio.h>
#include <string.h>
// Author structure
struct Author {
char name[50];
char country[50];
};
// Book structure
struct Book {
char title[100];
struct Author author;
int year;
float price;
};
// Function to search books by author name
void searchByAuthor(struct Book books[], int n, char authorName[]) {
int found = 0;
printf("nBooks by author "%s":n", authorName);
for (int i = 0; i < n; i++) {
if (strcmp(books[i].author.name, authorName) == 0) {
printf("Title: %s, Year: %d, Price: %.2f, Country: %sn",
books[i].title,
books[i].year,
books[i].price,
books[i].author.country);
found = 1;
}
}
if (!found) {
printf("No books found by this author.n");
}
}
int main() {
int n = 3; // Number of books
struct Book books[3];
// Input book details
for (int i = 0; i < n; i++) {
printf("nEnter details for book %d:n", i + 1);
printf("Title: ");
scanf(" %[^n]", books[i].title); // read string with spaces
printf("Author Name: ");
scanf(" %[^n]", books[i].author.name);
printf("Author Country: ");
scanf(" %[^n]", books[i].author.country);
printf("Year: ");
scanf("%d", &books[i].year);
printf("Price: ");
scanf("%f", &books[i].price);
}
// Search by author
char searchName[50];
printf("nEnter author name to search: ");
scanf(" %[^n]", searchName);
searchByAuthor(books, n, searchName);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!