C++
Putting it together
Combine the cart functions with a menu.
Putting it together
All pieces are ready: the Product struct, the addItem, getSubtotal and printCart functions. Now we will combine them inside main to create two products in the cart, print the cart and show the total.
At this stage each function does its own job; main just calls them in order. A well-designed program scales by keeping functions small and focused. If you want to add a new feature to the cart later, you only need to change the relevant function.
All pieces together
When all parts of the cart application come together you get a real shopping flow: products are added, the cart is shown and the total is computed. Each function does one job well.
Later you can wrap this in a menu loop to offer choices to the user. The pattern do { ... } while (choice != 0); shows the menu again until 0 is entered. For now we will drive the flow with direct calls; you will see interactive menus in later projects.
Exercise Integrate the cart
Inside main add two products with cart.addItem, then call cart.printCart() and cart.getSubtotal() to print the cart and the total. Products: Notebook (25, 2) and Pen (10, 3). The output must be three lines: Notebook 25 2, Pen 10 3 and Total: 80.
Show example solution
#include <iostream>
#include <string>
#include <vector>
struct Product {
std::string name;
double price;
int quantity;
};
struct Cart {
std::vector<Product> items;
void addItem(Product p) {
items.push_back(p);
}
double getSubtotal() {
double sum = 0;
for (const auto& p : items) {
sum += p.price * p.quantity;
}
return sum;
}
void printCart() const {
for (const auto& p : items) {
std::cout << p.name << " " << p.price << " " << p.quantity << std::endl;
}
}
};
int main() {
Cart cart;
Product p1;
p1.name = "Notebook";
p1.price = 25.0;
p1.quantity = 2;
cart.addItem(p1);
Product p2;
p2.name = "Pen";
p2.price = 10.0;
p2.quantity = 3;
cart.addItem(p2);
cart.printCart();
std::cout << "Total: " << cart.getSubtotal() << std::endl;
return 0;
}
Test yourself
-
Write the main integration line
cart.printCart();
std::cout << "Total: " << ____ << std::endl;
Show answer
cart.printCart();
std::cout << "Total: " << cart.getSubtotal() << std::endl;
-
Which construct calls all pieces in the integration step?
// integrated flow
Show answer
main — main calls all functions in order.
-
Match each piece to its job
- Cart
- Holds all the data
- addItem
- Adds to the cart
- printCart
- Shows the cart
- getSubtotal
- Returns the total
Next lesson: C-style arrays