โ† All C# lessons

C# / Chapter 02

Conditionals, Patterns & Loops

Control execution with boolean logic, switch expressions, loops, pattern matching, and careful boundary handling.

Chapter roadmap

Control execution with boolean logic, switch expressions, loops, pattern matching, and careful boundary handling. Work through the concepts in order, type every example yourself, and keep a short debugging log that records predictions, errors, fixes, and what each fix taught you.

Learning objectives

  • Write branches and compound conditions
  • Use switch expressions
  • Choose loop structures
  • Apply pattern matching and validation

02.1

if/else and boolean logic

Conditions use comparisons and logical operators &&, ||, and !. Place the most specific conditions first and use braces consistently. Nullable booleans require an explicit policy because true, false, and unknown are distinct states.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
int score = 84;
string grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else grade = "Revise";
Console.WriteLine(grade);
Result
B
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

02.2

switch expressions and patterns

A switch expression maps an input to a result. Patterns can match constants, types, relational ranges, and property shapes. Arms are checked in order and the discard pattern _ provides a deliberate fallback.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
int temperature = 72;
string label = temperature switch
{
    < 32 => "Freezing",
    < 60 => "Cool",
    <= 80 => "Comfortable",
    _ => "Hot"
};
Console.WriteLine(label);
Result
Comfortable
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

02.3

for, while, and foreach

for fits indexed repetition, while fits condition-controlled work, and foreach reads every item in an enumerable sequence. A loop should make termination obvious. foreach variables are read-only bindings, though referenced objects may still be mutable.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
int total = 0;
foreach (int value in new[] { 4, 8, 3, 5 })
{
    total += value;
}
Console.WriteLine(total);
Result
20
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

02.4

Nested loops and validation

Nested loops create grids and compare combinations; their work multiplies, so limits matter. Input loops should explain the rule and repeat until valid. break and continue are useful for small exceptional paths but should not hide the main loop logic.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
int number;
do
{
    Console.Write("Enter 1-10: ");
}
while (!int.TryParse(Console.ReadLine(), out number) || number is < 1 or > 10);
Console.WriteLine($"Accepted {number}");
Result
Enter 1-10: 14
Enter 1-10: 7
Accepted 7
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

Chapter assignments

Complete these in order. Later assignments assume that earlier skills are working. Do not only test the sample values; design tests that challenge boundaries, missing values, incorrect types, empty collections, and other likely failures.

  1. A2.1

    Classify a date or numeric value with a switch expression and include complete boundary tests.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

  2. A2.2

    Build a validated repeating menu with at least five operations and a clear quit path.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

  3. A2.3

    Analyze a sequence using foreach to calculate totals, extremes, category counts, and percentage results.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

  4. A2.4

    Use nested loops to generate a multiplication grid and a second aligned text pattern.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

Chapter project

Tournament Tracker

Tournament Tracker โ€” Accept player names and round scores, validate ranges, calculate standings after each round, resolve ties using a documented rule, and allow a new tournament without restarting.

Required process

  1. Write a short specification listing inputs, outputs, rules, and failure cases.
  2. Break the work into small functions, queries, modules, or classes appropriate to the language.
  3. Build the smallest working version before adding optional features.
  4. Test normal, boundary, empty, and invalid cases and record the results.
  5. Refactor names and duplication, then write a concise user guide.

Key terms

  • branch
  • logical operator
  • switch expression
  • pattern
  • relational pattern
  • loop
  • enumerable
  • boundary
  • validation