#csharp #dotnet #backend

Day 3: Control Flow (if, switch, loops)

Welcome to Day 3. Today we’re learning how to make decisions and repeat actions using Control Flow.

If / Else

The bread and butter of programming logic. C#‘s syntax is very similar to JavaScript or Java.

int score = 85;

if (score >= 90) 
{
    Console.WriteLine("A Grade");
} 
else if (score >= 80) 
{
    Console.WriteLine("B Grade");
} 
else 
{
    Console.WriteLine("Needs Improvement");
}

Switch Statements & Expressions

When checking multiple discrete values, switch is much cleaner than a massive if/else block.

Modern C# (C# 8+) introduced Switch Expressions, which are wonderfully concise:

string role = "Admin";

// Classic Switch Statement
switch (role) 
{
    case "Admin":
        Console.WriteLine("Full Access");
        break;
    case "User":
        Console.WriteLine("Limited Access");
        break;
    default:
        Console.WriteLine("No Access");
        break;
}

// Modern Switch Expression (Returns a value directly!)
string message = role switch 
{
    "Admin" => "Full Access",
    "User" => "Limited Access",
    _ => "No Access" // The '_' acts as the default case
};

Console.WriteLine(message);

Loops

C# provides four main types of loops.

1. for Loop

Best when you know exactly how many times you want to loop.

for (int i = 0; i < 5; i++) 
{
    Console.WriteLine($"Iteration {i}");
}

2. while Loop

Best when you want to loop until a condition is no longer true.

int counter = 0;
while (counter < 3) 
{
    Console.WriteLine("Still going...");
    counter++;
}

3. do-while Loop

Like a while loop, but guaranteed to run at least once because the condition is checked at the end.

do 
{
    Console.WriteLine("This prints exactly once, even if false.");
} while (false);

4. foreach Loop

The most common loop you will use! It easily iterates over any collection or array.

string[] names = { "Alice", "Bob", "Charlie" };

foreach (string name in names) 
{
    Console.WriteLine($"Hello, {name}");
}

Challenge for Day 3

Write a program that uses a for loop to print numbers from 1 to 20. However, use a switch expression inside the loop to print “Fizz” if the number is divisible by 3, “Buzz” if divisible by 5, and “FizzBuzz” if divisible by 15. Otherwise, just print the number.

Tomorrow: Methods & Parameters.