Cart design
- C course
- Beginner
- Lesson 48/116
- 6 min
Design the structure and array for the shopping cart.
Project: Shopping cart
In this 5-lesson project you'll build a shopping cart. Each lesson adds one piece, and by the final lesson you'll have a complete app.
You'll use what you learned before:
- data structure with
struct intanddoublevariables- formatted output with
printf - loops with
for
You'll also learn cart_add, cart_subtotal and cart_list functions. Ready? Let's start.
The CartItem struct
We'll define a struct CartItem for a cart entry. Each item has a name, a price and a quantity. The cart is an array of this struct.
struct CartItem {
char name[32];
double price;
int qty;
};
struct CartItem cart[MAX_ITEMS];
int cart_size = 0;Here MAX_ITEMS is the maximum items the cart can hold. cart_size tracks the current count. As you add to the cart, cart_size grows.
Practice Write the cart skeleton
Write a C program. Define the struct CartItem (with char name[32]; double price; int qty;). Define struct CartItem cart[MAX_ITEMS]; and int cart_size = 0;. In main print printf("Cart ready\n"); and printf("%d items\n", cart_size);. Put #include <stdio.h> and #include <string.h> at the top. You can add #define MAX_ITEMS 10.
Starter code
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 10
// Define the CartItem struct: name[32], price, qty
// Define the cart array and the cart_size counter
int main(void) {
// Print the cart-ready message and the item count
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 10
struct CartItem {
char name[32];
double price;
int qty;
};
struct CartItem cart[MAX_ITEMS];
int cart_size = 0;
int main(void) {
printf("Cart ready\n");
printf("%d items\n", cart_size);
return 0;
}Expected output
Cart ready 0 items
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a cart need first?
struct CartItem { ... };
struct CartItem cart[MAX_ITEMS];- A struct and an array Correct answer
- A database
- A file
- A pointer
Explanation: A cart starts with a struct and an array.
2 Complete the struct definition
struct CartItem {
char name[32];
double price;
int ____;
};
struct CartItem {
char name[32];
double price;
int qty;
};
Explanation: qty holds the quantity.
3 Match the cart pieces
| Term | Meaning |
|---|---|
struct CartItem |
Item struct |
cart[MAX_ITEMS] |
Cart array |
cart_size |
Item count |
MAX_ITEMS |
Upper bound |