C
Listing the cart
Write the function that prints the cart items formatted.
The cart_list function
In this lesson we'll write the cart_list function. It prints all cart items in a formatted way.
void cart_list(void) {
for (int i = 0; i < cart_size; i++) {
printf("%s %.2f x %d = %.2f\n",
cart[i].name, cart[i].price, cart[i].qty,
cart[i].price * cart[i].qty);
}
}
Each line shows an item: name, price, quantity and subtotal. This output tells the user what's in the cart. We iterate with for and print each line.
Formatted output
When printing money values, using %.2f is a good habit; it shows two decimal digits. Currencies usually have two digits.
printf("%s %.2f x %d = %.2f\n",
"Apple", 2.50, 3, 7.50);
// Output: Apple 2.50 x 3 = 7.50
Here %s is name, %.2f is price, %d is quantity and the last %.2f is subtotal. Specifier order must match variable order.
Exercise List the cart
Write the cart_list function: void cart_list(void). With for (int i = 0; i < cart_size; i++) print each item using printf("%s %.2f x %d = %.2f\n", cart[i].name, cart[i].price, cart[i].qty, cart[i].price * cart[i].qty);. main already calls cart_list(); just complete the function. Expected output: Apple 2.50 x 3 = 7.50 / Bread 5.00 x 1 = 5.00.
Show example 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;
void cart_add(const char *name, double price, int qty) {
if (cart_size >= MAX_ITEMS) return;
strcpy(cart[cart_size].name, name);
cart[cart_size].price = price;
cart[cart_size].qty = qty;
cart_size++;
}
double cart_subtotal(void) {
double sum = 0;
for (int i = 0; i < cart_size; i++) {
sum += cart[i].price * cart[i].qty;
}
return sum;
}
void cart_list(void) {
for (int i = 0; i < cart_size; i++) {
printf("%s %.2f x %d = %.2f\n", cart[i].name, cart[i].price, cart[i].qty, cart[i].price * cart[i].qty);
}
}
int main(void) {
cart_add("Apple", 2.50, 3);
cart_add("Bread", 5.00, 1);
cart_list();
return 0;
}
Test yourself
-
Match the list pieces
- %s
- Name
- %.2f
- Price
- %d
- Quantity
- price * qty
- Subtotal
-
What does cart_list print?
void cart_list(void) {
for (...) {
printf("%s %.2f x %d", ...);
}
}
- Only the name
- Only the price
- Only the quantity
- Name, price, quantity and subtotal
Show answer
Name, price, quantity and subtotal — cart_list prints all information of each item.
-
Print the item name
printf("____ %.2f x %d = %.2f
", cart[i].name, cart[i].price, cart[i].qty, cart[i].price * cart[i].qty);
Show answer
printf("%s %.2f x %d = %.2f
", cart[i].name, cart[i].price, cart[i].qty, cart[i].price * cart[i].qty);
Next lesson: Putting it together