C
Calculating totals
Learn to compute the subtotal and the tax-inclusive total.
The cart_subtotal function
In this lesson we'll write cart_subtotal. This function sums price × quantity for every cart item and returns it as double.
double cart_subtotal(void) {
double sum = 0;
for (int i = 0; i < cart_size; i++) {
sum += cart[i].price * cart[i].qty;
}
return sum;
}
Here we iterate the cart with for and add each item's subtotal to sum. Tax and grand total are then computed from this subtotal.
Tax and grand total
Once you have the subtotal, computing tax and total is easy. Multiply the subtotal by a rate (e.g. 0.18) for tax, then add for the total.
double sub = cart_subtotal();
double tax = sub * 0.18;
double total = sub + tax;
printf("Subtotal: %.2f\n", sub);
printf("Tax: %.2f\n", tax);
printf("Total: %.2f\n", total);
%.2f shows two decimal digits; good for currencies. Our cart has Apple 2.50 × 3 = 7.50 and Bread 5.00 × 1 = 5.00; subtotal 12.50, tax 2.25, total 14.75.
Exercise Print the totals
Write the cart_subtotal function: double cart_subtotal(void). Inside define double sum = 0;, use for (int i = 0; i < cart_size; i++) to add sum += cart[i].price * cart[i].qty; and return sum;. main already makes the call; just complete the function. Expected output: Subtotal: 12.50 / Tax: 2.25 / Total: 14.75.
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;
}
int main(void) {
cart_add("Apple", 2.50, 3);
cart_add("Bread", 5.00, 1);
double sub = cart_subtotal();
double tax = sub * 0.18;
double total = sub + tax;
printf("Subtotal: %.2f\n", sub);
printf("Tax: %.2f\n", tax);
printf("Total: %.2f\n", total);
return 0;
}
Test yourself
-
What does cart_subtotal return?
double cart_subtotal(void) {
...
return sum;
}
- The tax amount
- The number of cart items
- The subtotal of all items
- The most expensive item
Show answer
The subtotal of all items — cart_subtotal returns the subtotal.
-
Compute the tax
double sub = cart_subtotal();
double tax = sub ____ 0.18;
Show answer
double sub = cart_subtotal();
double tax = sub * 0.18;
-
Match the total pieces
- cart_subtotal
- Subtotal
- tax = sub * 0.18
- Tax
- total = sub + tax
- Total
- %.2f
- Two decimals
Next lesson: Listing the cart