C
Model design
Design the skeleton of Book and Member structs.
Project: Library app
In this five-lesson project you'll build a library application. Each lesson adds a piece; by the final lesson you'll have a menu-driven program. You'll set up book and member models, the library collection, checkout, search and the menu in turn.
You'll use what you learned in earlier groups: structs, function pointers and strings. In this first lesson you'll design the skeleton of the Book and Member structs. Each lesson's starting code includes the previous lesson's solution; the code grows cumulatively.
Book and Member structs
A struct groups related data. For Book, title (char title[64]), year (int year) and borrowed state (int borrowed) are enough. Member gets name and id similarly.
Example: typedef struct { char title[64]; int year; int borrowed; } Book;. With typedef you can write Book directly instead of struct Book. This improves readability. A 64-byte title fits most book names; the borrowed field works as 0 (on shelf) or 1 (checked out).
Exercise Write Book and Member structs
Write typedef struct { char title[64]; int year; int borrowed; } Book; and typedef struct { char name[64]; int id; } Member;. Write void print_book(Book *b) with printf("Book: %s (%d)\n", b->title, b->year); inside. In main add Book b = {"C Tutorial", 2024, 0}; and print_book(&b);. Include <stdio.h> and <string.h>.
Show example solution
#include <stdio.h>
#include <string.h>
typedef struct {
char title[64];
int year;
int borrowed;
} Book;
typedef struct {
char name[64];
int id;
} Member;
void print_book(Book *b) {
printf("Book: %s (%d)\n", b->title, b->year);
}
int main(void) {
Book b = {"C Tutorial", 2024, 0};
print_book(&b);
return 0;
}
Test yourself
-
Which field in Book holds the borrowed state?
- int year
- char title[64]
- int borrowed
- char author[32]
Show answer
int borrowed — The borrowed field holds 0 or 1 for borrowed state.
-
Complete the Book struct
typedef struct {
char title[64];
int year;
____ borrowed;
} Book;
Show answer
typedef struct {
char title[64];
int year;
int borrowed;
} Book;
-
Match fields to purpose
- title[64]
- Book title
- year
- Publication year
- borrowed
- Borrowed state
- id
- Member id
Next lesson: Library module