Calculating totals
Learn to compute the subtotal and the tax-inclusive total.
Calculating totals
To compute the subtotal of the products in the cart we will write a GetSubtotal method. Each product contributes Price * Quantity; we walk all products and sum these to get the subtotal.
This is a classic accumulation pattern: start with double sum = 0;, walk each product with foreach, and add with sum += p.Price * p.Quantity. Finally return sum; returns the result.
Subtotal and tax
The subtotal is the amount before tax and extra fees. To get the tax-inclusive total you use subtotal * (1 + taxRate); for an 18% tax you apply a 1.18 multiplier.
In this project GetSubtotal returns only the subtotal; the taxed total can be computed in Main. Separating the two makes it easy to update just the multiplier when the tax rate changes.
Exercise Write the GetSubtotal method
Add a GetSubtotal method to the Cart class. Its signature must be public double GetSubtotal(). In the body start with double sum = 0;, walk each product with foreach (var p in items), add with sum += p.Price * p.Quantity, and return with return sum;. Main adds two products and prints GetSubtotal.
Show example solution
Inside Cart write public double GetSubtotal() { double sum = 0; foreach (var p in items) { sum += p.Price * p.Quantity; } return sum; }
Example solution:
using System;
using System.Collections.Generic;
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public int Quantity { get; set; }
}
class Cart
{
private List<Product> items = new List<Product>();
public void AddProduct(Product product)
{
items.Add(product);
}
public double GetSubtotal()
{
double sum = 0;
foreach (var p in items)
{
sum += p.Price * p.Quantity;
}
return sum;
}
}
class Program
{
static void Main()
{
var cart = new Cart();
cart.AddProduct(new Product { Name = "Notebook", Price = 25, Quantity = 2 });
cart.AddProduct(new Product { Name = "Pen", Price = 10, Quantity = 3 });
Console.WriteLine(cart.GetSubtotal());
}
}
Test yourself
-
Write the foreach loop variable
double sum = 0; foreach (____ p in items) { sum += p.Price * p.Quantity; }Show answer
double sum = 0; foreach (var p in items) { sum += p.Price * p.Quantity; } -
What does subtotal mean?
// in a cart- Tax-inclusive total
- Pre-tax intermediate total
- Number of items
- Discount amount
Show answer
Pre-tax intermediate total — Correct. Subtotal is the pre-tax intermediate total.
-
Match each concept to its meaning
- Subtotal
- Pre-tax total
- Tax
- Tax rate
- Total
- Tax-inclusive total
- Quantity
- Item count