Skip to main content

📝 Lesson 3.1: Making Decisions with if and switch

Real programs react. They do one thing if a user is old enough, another if not. In this lesson you'll teach your programs to make choices based on conditions.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Run code conditionally with if, else if, and else
  • Write conditions using the comparison and logical operators from Module 2
  • Understand code blocks and why braces and indentation matter
  • Choose among many fixed options with a switch
  • Recognize the modern switch expression and the ternary operator

Estimated Time: 45 minutes

Project: Build a program that grades a score and reacts to a menu choice.

In This Lesson

Programs That Branch

Until now, your programs have run straight through, top to bottom. But decisions let a program take different paths depending on the situation — this is called control flow.

graph TD A["Check a condition"] --> B{"Is it true?"} B -->|"Yes"| C["Do one thing"] B -->|"No"| D["Do something else"] C --> E["Continue the program"] D --> E style A fill:#eff6ff,stroke:#3b82f6,stroke-width:2px style E fill:#e8f5e9,stroke:#4CAF50,stroke-width:2px

The condition is always something that evaluates to a bool — exactly the true/false results you built with comparison and logical operators in Lesson 2.2.

The if Statement

An if statement runs a block of code only when its condition is true. The shape is: the keyword if, a condition in parentheses, and a block in braces:

int age = 20;

if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}

If the condition age >= 18 is true, the line inside the braces runs. If it's false, C# skips the whole block and moves on. With age set to 20, this prints:

Output:

You are an adult.

Change age to 15 and nothing prints — the condition is false, so the block is skipped.

💡 Read it aloud: "If age is at least 18, then print 'You are an adult.'" C# code often maps directly onto plain-English sentences like this.

else and else if

An else block runs when the if condition is false — the "otherwise" path:

int age = 15;

if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are a minor.");
}

Exactly one of the two blocks runs — never both, never neither.

Choosing among several options with else if

To test several conditions in order, chain them with else if. C# checks each condition top to bottom and runs the first one that's true, then stops checking the rest:

int score = 82;

if (score >= 90)
{
    Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
    Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
    Console.WriteLine("Grade: C");
}
else
{
    Console.WriteLine("Grade: F");
}

Output (score is 82):

Grade: B

⚠️ Order matters

Because C# stops at the first true condition, put the most specific / highest conditions first. If you checked score >= 70 before score >= 90, then a 95 would match the 70 test first and be mislabeled a "C". The >= 90 check must come before >= 80, which comes before >= 70.

💡 Combining conditions

Conditions can use the logical operators from Lesson 2.2. For example, a single range check:

if (score >= 80 && score < 90)
{
    Console.WriteLine("Solid B work!");
}

Blocks, Braces, and Style

The braces { } group statements into a block — all the code that belongs to the if. You can put many statements inside one block:

if (age >= 18)
{
    Console.WriteLine("You are an adult.");
    Console.WriteLine("You can vote.");
    Console.WriteLine("Welcome!");
}

⚠️ Always use braces

C# technically lets you skip the braces for a single statement, but this is a well-known source of bugs. Always include the braces — it prevents mistakes when you later add a second line, and keeps every if looking consistent.

✅ Indentation is for humans

Indenting the code inside a block doesn't change how the program runs, but it makes the structure obvious at a glance. Your editor will usually indent for you. Consistent indentation is a mark of readable, professional code.

Nested if

You can place an if inside another if to check a follow-up condition only when the first is true:

if (hasTicket)
{
    if (age >= 18)
    {
        Console.WriteLine("Enjoy the show!");
    }
    else
    {
        Console.WriteLine("Ticket holders must be 18+.");
    }
}

Nesting is useful, but too much of it gets hard to read. Often you can flatten it by combining conditions with && instead.

The switch Statement

When you're comparing one value against many fixed possibilities, a long else if chain gets repetitive. A switch is cleaner for this:

int day = 3;

switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    default:
        Console.WriteLine("Another day");
        break;
}

Output (day is 3):

Wednesday

How it works:

  • switch (day) — the value being tested.
  • Each case lists a value to match. When one matches, its statements run.
  • break; ends that case and exits the switch.
  • default: is the catch-all, running when no case matches (like a final else).

⚠️ Don't forget break;

In a classic switch statement, each case must end with break; (or another exit). Forgetting it is a common error the compiler will usually flag. Each case should clearly finish before the next begins.

💡 if or switch?

Use switch when testing one variable against several specific, fixed values (a day number, a menu choice, a letter). Use if/else if for ranges or more complex conditions (like score >= 80) that aren't a single exact match.

Modern Shortcuts

You'll encounter two compact forms in modern C#. You don't have to use them yet, but it helps to recognize them.

The switch expression

A newer, tidier form of switch that produces a value. The => means "results in," and _ is the catch-all:

int day = 3;

string name = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    _ => "Another day"
};

Console.WriteLine(name);   // Wednesday

The ternary operator

For a simple either/or choice, the ternary operator ?: picks between two values in one line. Read it as "condition ? value-if-true : value-if-false":

int age = 20;
string status = (age >= 18) ? "adult" : "minor";
Console.WriteLine(status);   // adult

✅ Keep it readable

These shortcuts are great for short, clear choices. If a ternary or switch expression starts getting complicated, fall back to a regular if/else — readability always wins.

Exercise & Quiz

🏋️ Exercise: Grade & Menu

Objective: Use both if/else if (for a range) and switch (for fixed choices).

Instructions:

  1. Create a new project called Decisions.
  2. Ask the user for a test score (0–100), read it with int.Parse, and print a letter grade using if/else if: A (90+), B (80–89), C (70–79), D (60–69), else F.
  3. Then ask them to pick a menu option 1, 2, or 3, and use a switch to print "Play", "Settings", or "Quit". Use default for anything else.

Starter Code:

Console.Write("Enter your score (0-100): ");
int score = int.Parse(Console.ReadLine());

// TODO: if / else if chain to print a letter grade

Console.Write("Choose a menu option (1-3): ");
int choice = int.Parse(Console.ReadLine());

// TODO: switch on choice to print Play / Settings / Quit
💡 Hint

For the grade, check the highest cutoff first (score >= 90), then work down. For the menu, switch (choice) with case 1:, case 2:, case 3:, each ending in break;, plus a default:.

✅ Solution
Console.Write("Enter your score (0-100): ");
int score = int.Parse(Console.ReadLine());

if (score >= 90)
{
    Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
    Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
    Console.WriteLine("Grade: C");
}
else if (score >= 60)
{
    Console.WriteLine("Grade: D");
}
else
{
    Console.WriteLine("Grade: F");
}

Console.Write("Choose a menu option (1-3): ");
int choice = int.Parse(Console.ReadLine());

switch (choice)
{
    case 1:
        Console.WriteLine("Play");
        break;
    case 2:
        Console.WriteLine("Settings");
        break;
    case 3:
        Console.WriteLine("Quit");
        break;
    default:
        Console.WriteLine("Unknown option");
        break;
}

Sample run:

Enter your score (0-100): 84
Grade: B
Choose a menu option (1-3): 3
Quit

🎯 Quick Quiz

Question 1: What kind of value must an if condition evaluate to?

Question 2: In an if / else if / else chain, how many blocks run?

Question 3: When is a switch statement the better choice over if/else if?

Summary

🎉 Key Takeaways

  • if (condition) { ... } runs a block only when the bool condition is true.
  • else handles the "otherwise" path; else if chains test conditions in order and run the first true one.
  • Order matters in an else if chain — check the most specific conditions first.
  • Always use braces { }, and indent consistently for readability.
  • switch cleanly compares one value to fixed case values (don't forget break;); modern switch expressions and the ternary ?: are compact alternatives.

📚 Additional Resources

🚀 What's Next?

Your programs can now choose between paths. Next, they'll learn to repeat work. In Lesson 3.2: Loops, you'll run code many times with for, while, and foreach — no copy-pasting required.

🎉 Decisions unlocked!

Branching is one of the two great powers of programming. Next up: the other one — repetition.