Data model
- C course
- Beginner
- Lesson 113/116
- 6 min
Set up the structs and arrays for the app.
Array of books
To manage multiple books you declare an array of struct Book. This is the catalog's core data model.
struct Book books[2] = {
{"Suç ve Ceza", 1866},
{"Sefiller", 1862}
};Here books holds two books. Each element has its own title and year members. With books[0].title you reach the first book's title. This structure provides the basis to expand the catalog.
Accessing array elements
In a struct Book array you access elements with [index], then members with .. The chain order matters.
printf("%s\n", books[0].title);
printf("%d\n", books[1].year);First books[0] gives the first book; then .title takes its title. This pattern is standard to process tabular data. You can loop over all books with a for loop.
Practice Create a two-book array
Declare struct Book books[2] and initialize with {{"War and Peace", 1869}, {"Anna Karenina", 1877}}. Print the first book's title and year with printf.
Starter code
#include <stdio.h>
struct Book {
char title[32];
int year;
};
int main(void) {
// Declare a two-book array; print the first book with printf
return 0;
}Sample solution
struct Book books[2] = {{"War and Peace", 1869}, {"Anna Karenina", 1877}};
printf("%s %d\n", books[0].title, books[0].year);Expected output
War and Peace 1869
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the best structure to hold two books together?
- An array Correct answer
- Two pointers
- Two separate variables
- Two structs
Explanation: An array lets you manage multiple structs under one name.
2 Match expression to meaning
| Term | Meaning |
|---|---|
books[0] |
First book |
books[1] |
Second book |
books[0].title |
First title |
books[1].year |
Second year |
3 Fill in the blank: array element
printf("%s
", books____);
printf("%s
", books[0].title);
Explanation: books[0].title gives the first book's title.