C# (.NET 8 LTS) track

Lesson 04 · Part 1: Basics

Control Flow

Branch and repeat work with conditionals, switch expressions and the main loop forms.

Part 1: Basics4 min readFree lesson

The flow of the program flows from top to bottom, branching with conditions and repeating with repeat. The switch expression, added after C# 8, provides clean pattern matching in the functional style.

Learning Objectives

  • Conditional branch to if / else if / else
  • Know the difference between the switch statement and the switch expression (=>)
  • Distinguish the use of for / while / do-while / foreach
  • Control repetition with break and continue

Key concepts

1) if / else if / else

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 in order from the top, so that only the branch that is true first is executed.

2) switch statement vs switch expression

statement type:

switch (day)
{
    case 1: Console.WriteLine("month"); break;
    case 2: Console.WriteLine("angry"); break;
    default: Console.WriteLine("?"); break;
}

expression type — C# 8+:

string name = day switch
{
    1 => "month",
    2 => "angry",
    _ => "?"        //default role
};

Since the expression type returns a value, it can be directly assigned to a variable, and there is no need for break. _ is a wildcard that “matches any value”.

3) for / while / do-while

  • for: Repeat with a set number of times
  • while: Repeat while the condition is true (possible 0 times)
  • do-while: Check conditions after executing once (at least once)
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 IEnumerable, such as an array or list. Suitable for simple traversal that does not require an index.

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

5) break / continue

  • break: Terminates the current loop immediately
  • continue: Skip current iteration to next iteration
for (int i = 1; i <= 10; i++)
{
    if (i == 5) break;       //Escape from i==5
    if (i % 2 == 0) continue;//Skip even numbers
    Console.WriteLine(i);    //1, 3 output
}

See as example

Example 1 — IfElse/Program.cs: Determining grade level

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}");

Execution result

Score: 85
Grade: B

Note: Since it is evaluated from top to bottom, you need to sort it from narrow condition or big value first to work as intended.

Example 2 — SwitchExpression/Program.cs: Day of the week

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);

Execution result

Day number (1~7): 3
Wednesday

Note: The switch expression will issue a warning if it does not cover all cases. Be sure to leave the default value as _.

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

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

//Countdown from 5 to 1
int n = 5;
while (n > 0)
{
    Console.Write($"{n} ");
    n--;
}
Console.WriteLine("Fire!");

Execution result

1~10 sum = 55
5 4 3 2 1 Fire!

Note: Accumulated variables must be initialized outside the loop for the results to persist.

Example 4 — Foreach/Program.cs: Array sum

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 score: {total}, average: {avg:F2}");

Execution result

Total score: 419, average: 83.80

Memo: Detailed usage of arrays is covered in Part 11. “Iterating over a bundle” is sufficient here.

Common Mistakes

  1. Confusing <= and < like for (int i = 0; i <= n; i++) — off-by-one bug.
  2. break is missing from the switch statement — it is not in the expression type, but the statement type is required.
  3. Infinite loop — break condition is missing in while (true).
  4. Modifying collection during foreach — exception occurred. Use for to fix.
  5. Incorrectly written as if (a == 0 || 1) — if (a == 0 || a == 1) is correct.

Cleanup

  • Branches: if/else and switch (recommended expression type)
  • Repeat: Count — for, Condition — while, At least 1 time — do-while, Collection — foreach
  • Escape to break, skip to continue
  • The switch expression + _ pattern is the recommended style in modern C#.

Try it yourself

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

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/Foreach/Foreach.csprojText
<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.csC#
//Iterate through the array with foreach and sum/average
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 score: {total}, average: {avg:F2}");
src/ForWhile/ForWhile.csprojText
<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.csC#
//Sum up with for, count down with while
int sum = 0;
for (int i = 1; i <= 10; i++)
    sum += i;
Console.WriteLine($"1~10 sum = {sum}");

int n = 5;
while (n > 0)
{
    Console.Write($"{n} ");
    n--;
}
Console.WriteLine("Fire!");
src/IfElse/IfElse.csprojText
<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.csC#
//Determination of grade level
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.csC#
//switch expression - day number in Korean
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.csprojText
<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>

Assignment

Problem 1 — Sum from 1 to N

  • Reference solution: shown below
  • Key concepts: for iteration, cumulative sum

Requirements

  • Receives the integer N
  • Calculate and print 1 + 2 + ... + N
  • If N is 0 or less, “Input below 0 cannot be processed.” prints and exits

Expected output

N: 10
Sum of 1 to 10 = 55

Hint

  • for (int i = 1; i <= n; i++) sum += i;
  • You can verify input first and then terminate early with return; (also possible with top-level statements)

Problem 2 — FizzBuzz (1~30)

  • Reference solution: shown below
  • Key concepts: for, %, if/switch expressions

Requirements

  • Print from 1 to 30,
  • If it is a multiple of 3, it is Fizz
  • If it is a multiple of 5, it is Buzz
  • If both, FizzBuzz
  • The rest remain as numbers.

Expected output

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

Hint

  • Check i % 15 == 0 first, or process it as a pattern in the switch expression
  • You can express it neatly in one expression by using the switch expression + when clause:
    string line = i switch
    {
        _ when i % 15 == 0 => "FizzBuzz",
        _ when i % 3 == 0  => "Fizz",
        _ when i % 5 == 0  => "Buzz",
        _ => i.ToString()
    };
    

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

Homework01/Homework01.csprojText
<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>
Homework01/Program.csC#
//Sum from 1 to N
Console.Write("N: ");
int n = int.Parse(Console.ReadLine()!);

if (n <= 0)
{
    Console.WriteLine("Inputs below 0 cannot be processed.");
    return;
}

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

Console.WriteLine($"Sum of 1 to {n} = {sum}");
Homework02/Homework02.csprojText
<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>
Homework02/Program.csC#
// 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);
}

Learn this lesson with a mentor

Work through the C# (.NET 8 LTS) track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now