Structure Assignment 6 — Find the Total Price of a Collection of Books
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Total Price of a Collection of Books Using a Structure

📑 On this page:
  • Many books, one struct
  • Add them up in a loop
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to make an array whose elements are structs (a list of books)
  • How to loop over the array and reach into each book's price
  • Why the running total should be a float or double, not an int
  • Why braces around each book in the initializer help keep things readable
  • How to print a small table so you can see each book and the total side by side

Many books, one struct

So far we've had one book per variable. That's fine for a single record, but a real program usually has many. The natural way to hold many books is an array — but not an array of titles, and not an array of prices. An array where each element is a whole book. That's what struct book library[3]; gives you: three complete book records, each with its own title, author, and price.

Once you have that, adding up the prices is just a loop. Walk from index 0 to index 2, and for each one add library[i].price to a running total. The dot on library[i].price reads like "the price of the i-th book" and that's exactly what it is. Nothing tricky.

One thing to watch: the total has to be a floating-point number. Prices have cents, and an int can't hold cents. If you use an int, 45.99 becomes 45, and your total will be off by a few cents per book — which doesn't sound like much until you have a hundred books. Use a float or double. I'll use double in the example, since it's a bit more precise and the extra memory costs nothing.

💡 In one line: declare struct book library[3];, fill each element, then loop total += library[i].price for i = 0..2.

Three book structs side by side, with arrows to a running total that starts at 0 and grows to 45.99, then 71.98, then 118.97.

Add them up in a loop

The whole idea in pseudocode is four lines:

total = 0.0
for i = 0 to 2:
    total = total + library[i].price
print total
                                

Four lines, and the rest is just filling in the books and printing. The loop bound is 3 here, but it's cleaner to write sizeof(library) / sizeof(library[0]) — same trick we used for the marks array. That way, if you later decide to hold five books instead of three, the loop still works without touching it.

Book Price Running total
The C Programming Language45.9945.99
Clean Code25.9971.98
The Pragmatic Programmer46.99118.97

You can see how the total climbs with each book. That's the whole algorithm in a table — the loop does exactly this, one book at a time.

Complete C Program

Program: total price of a small library

#include <stdio.h>

struct book {
    char  title[100];
    char  author[50];
    float price;
};

int main(void) {
    struct book library[3] = {
        {"The C Programming Language", "Kernighan & Ritchie", 45.99f},
        {"Clean Code",                 "Robert C. Martin",     25.99f},
        {"The Pragmatic Programmer",   "Hunt & Thomas",        46.99f}
    };

    int count = sizeof(library) / sizeof(library[0]);
    double total = 0.0;

    printf("Book Collection\n");
    printf("---------------\n");
    for (int i = 0; i < count; i++) {
        printf("%-30s  %.2f\n", library[i].title, library[i].price);
        total += library[i].price;
    }

    printf("---------------\n");
    printf("Total: %.2f\n", total);

    return 0;
}
                                    

And here's a version that asks the user to type the prices, which is closer to how a real program would work:

Variant: read prices from the user

#include <stdio.h>

struct book {
    char  title[100];
    float price;
};

int main(void) {
    struct book library[3];

    for (int i = 0; i < 3; i++) {
        printf("Enter title of book %d: ", i + 1);
        scanf(" %99[^\n]", library[i].title);
        printf("Enter price of book %d: ", i + 1);
        scanf("%f", &library[i].price);
    }

    double total = 0.0;
    printf("\nBook Collection\n");
    printf("---------------\n");
    for (int i = 0; i < 3; i++) {
        printf("%-30s  %.2f\n", library[i].title, library[i].price);
        total += library[i].price;
    }
    printf("---------------\n");
    printf("Total: %.2f\n", total);

    return 0;
}
                                    

The first version is what the assignment asks for — a small set of books with prices we already know, and a total. The second shows the same idea with user input, which is closer to real use. Both loops are identical. That's the pattern: read or fill, then loop, then add.

Program Output

Book Collection
---------------
The C Programming Language     45.99
Clean Code                     25.99
The Pragmatic Programmer       46.99
---------------
Total: 118.97
                                

If you run the second version, you'll see prompts asking for the title and price of each book, and then the same table printed at the end. The total updates as you add books with different prices — try a book priced at 100 and watch the total jump.

Step-by-Step Explanation

Let's walk through the first version.

1. The struct

Same struct book as before — title, author, price. Nothing new here. The struct is just the shape of one book.

2. The array of books

struct book library[3] = { ... }; declares three books and fills them all at once. Each inner brace {"Title", "Author", 45.99f} is one book. The outer braces hold all three. This is just the one-line fill from the last assignment, repeated three times, with an extra layer of braces.

3. The count trick

int count = sizeof(library) / sizeof(library[0]); works out how many books are in the array. It's sizeof(library) (the whole array in bytes) divided by sizeof(library[0]) (one element in bytes) — which gives 3. I could just write 3 directly, but if you ever change the array from 3 books to 5, the loop still works without touching it. It's a small habit that saves small bugs.

4. The running total

double total = 0.0; starts at zero. Each loop iteration adds library[i].price to it. After the first iteration the total is 45.99, after the second it's 71.98, after the third it's 118.97. That's exactly what the table up above shows.

5. The printf inside the loop

There's an extra printf inside the loop, before the total += .... It prints each book's title and price on its own line, so you can see the list and the total side by side. The %-30s is just formatting — it left-aligns the title in a 30-character column, so the prices line up neatly. You could leave this out and only print the total, but a little extra output makes the program easier to check.

6. Why double, not int, for the total

If total were an int, each addition of a price like 45.99 would chop off the .99 and only add 45. Three books would give you 116 instead of 118.97 — off by almost three dollars. Using double keeps the cents. It's the same lesson as the average-marks program: money and averages need floating point.

7. Why the outer braces are needed

The outer braces say "here comes the whole array", and the inner braces say "here comes one book". Without the inner braces, the compiler would try to line up all the values in a flat list — the first value would go to library[0].title, the second to library[0].author, the third to library[0].price, and the fourth would try to go to library[1].title but the type wouldn't line up because the price slot got a string. It would fail to compile. The inner braces are how you say "these three values belong to one book, not to a flat sequence".

🎯 Remember this: struct book library[3]; is an array of three book records. Loop over it with library[i].price. Keep the total in a double. Use braces around each book in the initializer. The size trick sizeof(library) / sizeof(library[0]) keeps the loop honest if you change the size.

Frequently Asked Questions

1. Can I add more books without changing the loop?

Yes, as long as you change the array size in the declaration and use sizeof(library) / sizeof(library[0]) for the loop bound. That expression always gives the current array size, so the loop adapts automatically. If you hardcoded 3 in the loop, you'd have to change it every time the array size changes.

2. What if I use int instead of double for the total?

You'll lose the cents. Each total += library[i].price would truncate 45.99 to 45 before adding. Three books at 45.99, 25.99, 46.99 would give 45 + 25 + 46 = 116, not 118.97. For a single small library the difference is only a couple of dollars, but for a bigger collection it adds up. Always use float or double for money, or better yet, work in integer cents.

3. Why do I need the braces around each book?

Because a struct is itself a group of values. Without the inner braces, the compiler can't tell where one book ends and the next begins. The inner braces say "these three values are one book". If you leave them out, you'll get a confusing compile error about type mismatch, usually pointing to the price field getting a string value.

4. Can I fill each book one at a time instead of all at once?

Yes. Instead of the big initializer list, you can write library[0].price = 45.99f; strcpy(library[0].title, "The C Programming Language"); and so on for each book. Or you can loop over i and read from the user with scanf, which is what the second version does. The initializer style is shorter and neater for known data; the loop style is what you need when the data comes from the user.

5. What is %-30s doing in the printf?

It left-aligns a string in a 30-character column. The %- means "left-aligned", the 30 means "at least 30 characters wide", and the s means "string". So "Clean Code" (10 characters) gets 20 spaces after it before the price starts, so all the prices line up vertically. Without it, the prices would be at different columns depending on how long the title is, and the table would look messy.

6. What if I want the total in cents rather than dollars?

Store the price in cents as an long long or int field, and sum it in cents. Then divide by 100.0 at the end to print the dollar amount. This is how real point-of-sale software works — you never accumulate cents in a float because the small rounding errors eventually show up on the bill. It's a habit worth learning early.

💡 Tip: After this, try adding a quantity field to the struct and computing total += library[i].price * library[i].quantity instead of just the price. Now each book contributes to the total based on how many copies you have. It's a small change that makes the program feel more like a real bookstore checkout.

📖 Related Tutorials

  • 4. Create a Structure to Represent a Book
  • 5. Initialize and Display the Details of a Book Using a Structure
  • 7. Create a Structure to Represent a Point in 2D Space
  • Array of Structures
  • Arrays Within Structure
  • Structure Initialization
  • Accessing Structure Members
  • All 25 Structure Assignments

Previous Topic: -->> 5. Initialize and Display the Details of a Book Using a Structure   ||   Next Topic: -->> 7. Create a Structure to Represent a Point in 2D Space


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.