🎯 What you will learn
- Use if/else and switch expressions
- Loop with for, while and foreach
- Combine conditions with && and ||
👋 Let’s get started!
Games are full of decisions and repetition: check for hits, spawn enemies every second 🔀. C# gives you all the tools — plus modern switch expressions.
🪜 Step by step
1. 🔀 if / else
Same shape as Java.
int hp = 15;
if (hp <= 0) Console.WriteLine("Defeated");
else if (hp < 20) Console.WriteLine("Low health! ❤️🩹");
else Console.WriteLine("Healthy");
2. 🎛️ switch expression
A compact way to choose a value.
string weather = "rain";
string outfit = weather switch
{
"rain" => "raincoat ☔",
"snow" => "boots ❄️",
_ => "sneakers 👟"
};
Console.WriteLine(outfit);
3. 🔁 Loops
for counts; foreach visits every item.
for (int i = 1; i <= 3; i++) Console.WriteLine($"Wave {i}");
string[] enemies = { "slime", "bat" };
foreach (var e in enemies) Console.WriteLine($"A {e} appears!");
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
FizzBuzz (a classic!)
for (int i = 1; i <= 15; i++)
{
string result = (i % 3, i % 5) switch
{
(0, 0) => "FizzBuzz",
(0, _) => "Fizz",
(_, 0) => "Buzz",
_ => i.ToString()
};
Console.Write(result + " ");
}Countdown
int t = 3;
while (t > 0)
{
Console.WriteLine(t);
t--;
}📖 Key words
Tap a card to flip it over!
- switch expression
- Chooses a value with => arms 🎛️
- _ (discard)
- Matches anything else 🗑️
- foreach
- Loops over each item 🔁
- %
- Remainder after dividing ➗
🏆 Challenge
Predict the output.
Challenge
int score = 72;
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
_ => "Keep going"
};
Console.WriteLine(grade);Knowledge Check Quiz
- How many times does this loop run?
- What does _ mean in a switch expression?
- Which loop visits every item in an array?