CodeBlanks Logo Icon CodeBlanks

Model design

  • C course
  • Intermediate
  • Lesson 65/116
  • 6 min

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).

Practice 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>.

Starter code

main.c
#include <stdio.h>
#include <string.h>

// Define Book struct (title, year, borrowed)
// Define Member struct (name, id)
// Write print_book function

int main(void) {
    // Define a Book and print it with print_book
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

Book: C Tutorial (2024)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which field in Book holds the borrowed state?

  • int year
  • char title[64]
  • int borrowed Correct answer
  • char author[32]

Explanation: The borrowed field holds 0 or 1 for borrowed state.

2 Complete the Book struct

Question
typedef struct {
    char title[64];
    int year;
    ____ borrowed;
} Book;
Answer
typedef struct {
    char title[64];
    int year;
    int borrowed;
} Book;

Explanation: int borrowed; holds 0 or 1.

3 Match fields to purpose

Term Meaning
title[64] Book title
year Publication year
borrowed Borrowed state
id Member id

All lessons in Intermediate