← Back to Curriculum

Control Flow and Loops

📚 Lesson 3 of 15 ⏱ 35 min

Control Flow and Loops

35 min

C# provides standard control flow statements: if, else, switch, while, do-while, for, and foreach, enabling you to control program execution based on conditions and iterate over data. Control flow statements determine which code executes and in what order. Understanding control flow enables building logic into your programs. Control flow is fundamental to programming.

The if-else statement executes code conditionally based on boolean expressions. You can chain multiple conditions with else if. Logical operators (&&, ||, !) combine conditions. Understanding conditionals enables decision-making in code. Conditionals are essential for dynamic behavior.

The foreach loop is particularly useful for iterating over collections (arrays, lists, dictionaries) without managing indices. foreach is simpler and less error-prone than for loops for collections. foreach works with any type that implements IEnumerable. Understanding foreach enables clean iteration. foreach is preferred for collection iteration.

C# supports pattern matching in switch statements (C# 7.0+), enabling more powerful and expressive switch cases. Pattern matching can match types, values, and conditions. Switch expressions (C# 8.0+) enable switch as expressions. Understanding pattern matching enables modern C# code. Pattern matching makes switches more powerful.

Loops (while, do-while, for, foreach) enable repeating code. while checks condition before execution. do-while executes at least once. for provides initialization, condition, and increment. foreach iterates collections. Understanding loops enables processing data efficiently. Choose the right loop for your scenario.

Best practices include using meaningful condition names, avoiding deeply nested conditionals, using switch for multiple values, choosing appropriate loops, and using break/continue carefully. Understanding control flow enables writing clear, maintainable code. Control flow is essential for program logic.

Key Concepts

  • C# provides if, else, switch, while, do-while, for, and foreach.
  • if-else executes code conditionally based on conditions.
  • foreach loop iterates over collections without indices.
  • C# supports pattern matching in switch statements.
  • Loops enable repeating code execution.

Learning Objectives

Master

  • Using if-else for conditional execution
  • Iterating with for, while, and foreach loops
  • Using switch statements with pattern matching
  • Controlling loop execution with break and continue

Develop

  • Understanding program flow and logic
  • Choosing appropriate control structures
  • Writing clear, maintainable control flow

Tips

  • Use foreach for iterating collections—it's simpler and safer.
  • Use switch for multiple value comparisons.
  • Avoid deeply nested conditionals—extract methods instead.
  • Use meaningful boolean variable names for conditions.

Common Pitfalls

  • Using for loops when foreach would be simpler and safer.
  • Creating deeply nested conditionals, reducing readability.
  • Forgetting break in switch cases, causing fall-through.
  • Creating infinite loops by not updating loop variables.

Summary

  • C# provides standard control flow statements.
  • if-else enables conditional execution.
  • foreach is ideal for iterating collections.
  • Pattern matching makes switches more powerful.
  • Understanding control flow enables program logic.

Exercise

Write a program that demonstrates different control flow structures.

using System;

class Program
{
    static void Main(string[] args)
    {
        // If-else example
        int score = 85;
        if (score >= 90)
            Console.WriteLine("Grade: A");
        else if (score >= 80)
            Console.WriteLine("Grade: B");
        else
            Console.WriteLine("Grade: C");
        
        // For loop
        Console.WriteLine("\nCounting from 1 to 5:");
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(i);
        }
        
        // Foreach loop
        string[] fruits = { "Apple", "Banana", "Orange" };
        Console.WriteLine("\nFruits:");
        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}

Code Editor

Output