← Back to C# series
🟣
Basics
Basics · Prerequisite: previous lecture

04. Control Flow

Control program flow with branches and loops. Learn if·else·switch branching, for·while·do-while·foreach loops, and break·continue.

C#.NET 8basicscontrol flow
Duration
~1-1.5 hours
Level
📊 Beginner
Prerequisite
🎯 Previous lecture or equivalent
OUTCOME
Control program flow with branches and loops. Learn if·else·switch branching, for·while·do-while·foreach loops, and break·continue.

What you'll learn

  • 1Branch on conditions with `if` / `else if` / `else`
  • 2Know the difference between a `switch` statement and a **`switch` expression** (`=>`)
  • 3Pick between `for` / `while` / `do-while` / `foreach`
  • 4Control loops with `break` and `continue`

Overview

Programs flow top to bottom, but **branch** on conditions and **repeat** with loops. The switch expression added in C# 8 offers a clean, functional-style pattern match.

Core Concepts

1) `if` / `else if` / `else`

csharp
int score = 85;
if (score >= 90)        Console.WriteLine("A");
else if (score >= 80)   Console.WriteLine("B");
else if (score >= 70)   Console.WriteLine("C");
else                    Console.WriteLine("F");

Conditions are evaluated top to bottom, and only the **first true branch** runs.

2) `switch` statement vs `switch` expression

**Statement** form:

csharp
switch (day)
{
    case 1: Console.WriteLine("Mon"); break;
    case 2: Console.WriteLine("Tue"); break;
    default: Console.WriteLine("?"); break;
}

**Expression** form — C# 8+:

csharp
string name = day switch
{
    1 => "Mon",
    2 => "Tue",
    _ => "?"        // default case
};

The expression form **returns a value** so you can assign it directly, and `break` is not needed. `_` is the wildcard pattern that matches anything.

3) `for` / `while` / `do-while`

  • `for`: a fixed number of iterations
  • `while`: repeats while the condition is true (may run 0 times)
  • `do-while`: runs once then checks the condition (at least 1 iteration)
csharp
for (int i = 0; i < 3; i++)  Console.WriteLine(i);  // 0 1 2

int n = 3;
while (n > 0) { Console.WriteLine(n); n--; }        // 3 2 1

int m = 0;
do { Console.WriteLine("once"); } while (m > 0);    // just once

4) `foreach`

Iterates over arrays, lists, anything **`IEnumerable`**. Best for simple iteration where you don't need the index.

csharp
int[] nums = [10, 20, 30];
foreach (int x in nums)
    Console.WriteLine(x);

5) `break` / `continue`

  • `break`: **exits** the current loop immediately
  • `continue`: skips the current iteration and **moves to the next**
csharp
for (int i = 1; i <= 10; i++)
{
    if (i == 5) break;       // exit at i==5
    if (i % 2 == 0) continue;// skip evens
    Console.WriteLine(i);    // prints 1, 3
}

Examples

Example 1 — `IfElse/Program.cs`: grade evaluation

csharp
Console.Write("Score: ");
int score = int.Parse(Console.ReadLine()!);

string grade;
if (score >= 90)      grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else if (score >= 60) grade = "D";
else                  grade = "F";

Console.WriteLine($"Grade: {grade}");

**Output**

text
Score: 85
Grade: B

**Note:** Since it evaluates top to bottom, order **narrower conditions first** or **largest values first** for the intended behavior.

Example 2 — `SwitchExpression/Program.cs`: day number to name

csharp
Console.Write("Day number (1-7): ");
int day = int.Parse(Console.ReadLine()!);

string name = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 => "Saturday",
    7 => "Sunday",
    _ => "invalid input"
};

Console.WriteLine(name);

**Output**

text
Day number (1-7): 3
Wednesday

**Note:** Switch expressions warn if you don't cover all cases. Always include a `_` default.

Example 3 — `ForWhile/Program.cs`: `for` sum, `while` countdown

csharp
// sum from 1 to 10
int sum = 0;
for (int i = 1; i <= 10; i++)
    sum += i;
Console.WriteLine($"Sum 1..10 = {sum}");

// countdown 5 -> 1
int n = 5;
while (n > 0)
{
    Console.Write($"{n} ");
    n--;
}
Console.WriteLine("Liftoff!");

**Output**

text
Sum 1..10 = 55
5 4 3 2 1 Liftoff!

**Note:** Initialize the accumulator **outside the loop** so the result is preserved.

Example 4 — `Foreach/Program.cs`: sum an array

csharp
int[] scores = [78, 92, 64, 85, 100];

int total = 0;
foreach (int s in scores)
    total += s;

double avg = (double)total / scores.Length;
Console.WriteLine($"Total: {total}, Average: {avg:F2}");

**Output**

text
Total: 419, Average: 83.80

**Note:** Arrays are covered in detail in lecture 11. For now, "iterate over a collection" is enough.

Full example code (src/)

src/ForWhile/ForWhile.csproj

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics04</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

src/ForWhile/Program.cs

csharp
// for-sum, while-countdown
int sum = 0;
for (int i = 1; i <= 10; i++)
    sum += i;
Console.WriteLine($"Sum 1..10 = {sum}");

int n = 5;
while (n > 0)
{
    Console.Write($"{n} ");
    n--;
}
Console.WriteLine("Liftoff!");

src/Foreach/Foreach.csproj

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics04</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

src/Foreach/Program.cs

csharp
// foreach over an array, sum/avg
int[] scores = [78, 92, 64, 85, 100];

int total = 0;
foreach (int s in scores)
    total += s;

double avg = (double)total / scores.Length;
Console.WriteLine($"Total: {total}, Average: {avg:F2}");

src/IfElse/IfElse.csproj

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics04</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

src/IfElse/Program.cs

csharp
// grade evaluation
Console.Write("Score: ");
int score = int.Parse(Console.ReadLine()!);

string grade;
if (score >= 90)      grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else if (score >= 60) grade = "D";
else                  grade = "F";

Console.WriteLine($"Grade: {grade}");

src/SwitchExpression/Program.cs

csharp
// switch expression - day number to name
Console.Write("Day number (1-7): ");
int day = int.Parse(Console.ReadLine()!);

string name = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 => "Saturday",
    7 => "Sunday",
    _ => "invalid input"
};

Console.WriteLine(name);

src/SwitchExpression/SwitchExpression.csproj

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics04</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

Common Mistakes

  1. Confusing `<=` and `<` in `for (int i = 0; i <= n; i++)` — classic **off-by-one** bug.
  2. Forgetting `break` in a `switch` statement — not needed in expression form but required in statement form.
  3. Infinite loop — `while (true)` without a `break` condition.
  4. Modifying a collection during `foreach` — throws. Use `for` if you need to modify.
  5. Writing `if (a == 0 || 1)` — should be `if (a == 0 || a == 1)`.

Summary

  • Branching: `if`/`else` and `switch` (prefer the expression form)
  • Looping: count — `for`, condition — `while`, at-least-once — `do-while`, collections — `foreach`
  • Exit with `break`, skip with `continue`
  • Switch expression + `_` pattern is the recommended modern C# style

Practice

**Practice - 04. Control Flow**

Problem 1 — Sum from 1 to N

  • Project folder: `Homework01/`
  • Key concepts: `for` loop, running total

Requirements

  • Read integer `N`
  • Compute and print `1 + 2 + ... + N`
  • If `N` ≤ 0 print "Can't process input <= 0." and exit

Expected output

text
N: 10
Sum 1 to 10 = 55

Hints

  • `for (int i = 1; i <= n; i++) sum += i;`
  • Validate input first and exit early with `return;` (works in top-level statements too)

Problem 2 — FizzBuzz (1-30)

  • Project folder: `Homework02/`
  • Key concepts: `for`, `%`, `if`/`switch` expression

Requirements

  • Print 1 through 30, but
  • For multiples of 3: `Fizz`
  • For multiples of 5: `Buzz`
  • For multiples of both: `FizzBuzz`
  • Otherwise the number itself

Expected output

text
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
... (up to 30)

Hints

  • Check `i % 15 == 0` first, or use a `switch` expression with patterns
  • Switch expression + when clauses can express it neatly in one expression:

```csharp string line = i switch { _ when i % 15 == 0 => "FizzBuzz", _ when i % 3 == 0 => "Fizz", _ when i % 5 == 0 => "Buzz", _ => i.ToString() }; ```

Check your answer

Try it yourself, then compare against the [`answer/`](./answer/) folder.

Answer (answer/)

homework/answer/Homework01/Homework01.csproj

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics04</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

homework/answer/Homework01/Program.cs

csharp
// sum from 1 to N
Console.Write("N: ");
int n = int.Parse(Console.ReadLine()!);

if (n <= 0)
{
    Console.WriteLine("Can't process input <= 0.");
    return;
}

int sum = 0;
for (int i = 1; i <= n; i++)
    sum += i;

Console.WriteLine($"Sum 1 to {n} = {sum}");

homework/answer/Homework02/Homework02.csproj

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics04</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

homework/answer/Homework02/Program.cs

csharp
// FizzBuzz 1..30
for (int i = 1; i <= 30; i++)
{
    string line = i switch
    {
        _ when i % 15 == 0 => "FizzBuzz",
        _ when i % 3 == 0  => "Fizz",
        _ when i % 5 == 0  => "Buzz",
        _ => i.ToString()
    };
    Console.WriteLine(line);
}

Try It Yourself

bash
cd src/IfElse && dotnet run
cd ../SwitchExpression && dotnet run
cd ../ForWhile && dotnet run
cd ../Foreach && dotnet run

Next Lecture

[05_Methods](../05_%EB%A9%94%EC%84%9C%EB%93%9C/) — Group code into reusable methods.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗