Start learning free

LESSON 192 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in C#: Coupon Codes with a Dictionary

Practice Read the full explanation

Use a map as a fast lookup table for coupon discounts.

You start with:

        int subtotal = 100;
        string coupon = "SAVE20";
        Dictionary<string, int> coupons = new Dictionary<string, int>();
        coupons["SAVE10"] = 10;
        coupons["SAVE20"] = 20;
        coupons["SAVE50"] = 50;

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with Console.WriteLine(result).

Use coupons.ContainsKey(coupon) ? coupons[coupon] : 0: reading a missing key with [] would throw.

In C# "Total: $" + total converts the number to text for you.

        int subtotal = 100;
        string coupon = "SAVE20";
        Dictionary<string, int> coupons = new Dictionary<string, int>();
        coupons["SAVE10"] = 10;
        coupons["SAVE20"] = 20;
        coupons["SAVE50"] = 50;

        int discount = coupons.ContainsKey(coupon) ? coupons[coupon] : 0;
        int total = subtotal - discount;
        string result = "Total: $" + total;
        Console.WriteLine(result);

STEP 1 OF 4
    Ctrl + Enter to check

    C# · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in C#, explained

    Problem overview

    A shopper can type a coupon code at checkout. The program keeps a Dictionary<string, int> named coupons that maps each valid code to the amount it takes off: SAVE10 is 10, SAVE20 is 20 and SAVE50 is 50. Given a subtotal and the typed coupon, the program prints the total after the discount.

    With a subtotal of 100 and the code SAVE20, the discount is 20 and the output is:

    Total: $80
    

    If the code isn't in the dictionary, nothing is taken off. With the same subtotal and the code FREE, the output is Total: $100.

    Approach: look the code up, with a default

    A dictionary stores pairs: a key (the coupon text) and a value (the discount). Asking for the value of a key is a direct lookup, with no need to scan every coupon. The difficulty is the case where the shopper types a code that doesn't exist. In C#, reading a missing key with the indexer doesn't return a default value, it throws an exception. So the program checks first whether the key is there, and uses 0 as the discount when it isn't.

    Once the discount is known, the rest is simple arithmetic and text: total = subtotal - discount, then the text Total: $ followed by the total.

    Step by step

    1. Find the discount. coupons.ContainsKey(coupon) is true when the code is a key. Use it as the condition of a ternary: the value coupons[coupon] when it is true, 0 when it is false.
    2. Compute the total as subtotal - discount.
    3. Build the text. result is "Total: $" joined with total by +.
    4. Print result with Console.WriteLine.

    The solution in C#

            int subtotal = 100;
            string coupon = "SAVE20";
            Dictionary<string, int> coupons = new Dictionary<string, int>();
            coupons["SAVE10"] = 10;
            coupons["SAVE20"] = 20;
            coupons["SAVE50"] = 50;
    
            int discount = coupons.ContainsKey(coupon) ? coupons[coupon] : 0;
            int total = subtotal - discount;
            string result = "Total: $" + total;
            Console.WriteLine(result);
    

    The C# details worth a closer look:

    • Setting a value with the indexer. coupons["SAVE10"] = 10; adds the key if it is new and replaces the value if the key exists. coupons.Add("SAVE10", 10) behaves differently: calling it with a key that is already present throws an ArgumentException.
    • Reading a missing key throws. coupons["FREE"] throws a KeyNotFoundException with the message The given key 'FREE' was not present in the dictionary. That is why the lookup is guarded by ContainsKey. In the ternary, coupons[coupon] is only evaluated when the condition is true.
    • The ternary. condition ? a : b gives a if the condition is true and b otherwise. Both branches here are int, so the whole expression is an int.
    • Two shorter forms. TryGetValue does the check and the read in one lookup: coupons.TryGetValue(coupon, out int found) ? found : 0. And coupons.GetValueOrDefault(coupon) returns the default of the value type when the key is missing, which is 0 for int. Both give the same results as the lesson's version: 20 for SAVE20 and 0 for an unknown code. The lesson's two-step form is the most explicit.
    • The dictionary type. Dictionary<string, int> is in System.Collections.Generic. The first type argument is the key type and the second is the value type.

    Edge cases and common mistakes

    • An unknown code. "FREE" isn't a key, so the discount is 0 and the total equals the subtotal: Total: $100.
    • Case matters. Keys are compared exactly, so "save20" is not "SAVE20". With a lowercase code the discount is 0 and the output is Total: $100.
    • A null code. A dictionary doesn't accept null as a key to look up. ContainsKey(null) throws an ArgumentNullException. The lesson's code is always a text, so there is nothing to guard against.
    • A discount bigger than the subtotal. Nothing in the code limits the total to zero. With a subtotal of 30 and SAVE50, the output is Total: $-20. A real checkout would need a rule for this case, which this lesson doesn't ask for.
    • Indexing without the check. int discount = coupons[coupon]; works for the three known codes and throws for any other.
    • Adding the discount. The total is the subtotal minus the discount. Adding it would raise the price: SAVE20 would give 120.

    Testing

    • Subtotal 100 with "SAVE20" gives Total: $80.
    • Subtotal 100 with "SAVE50" gives Total: $50.
    • Subtotal 100 with "FREE" gives Total: $100.
    • Subtotal 100 with "save20" gives Total: $100.
    • Subtotal 30 with "SAVE50" gives Total: $-20.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free