Loops & Control Flow

🔷 C# Programming Lesson 5 Beginner

Loops repeat code blocks as long as a condition is satisfied. C# supports standard loops, range loops, and flow controls.

1 Loop Structures: while, do-while, and for

C# loops match standard constructs:

  • for: Best for iterating over fixed numeric ranges.
  • while: Evaluates conditions before checking execution blocks.
  • do-while: Executes execution blocks first, and then evaluates conditions.
2 Flow Control Tracing

Let's run a program illustrating loops, continue statements, and break constraints:

C# — Loops ▶ Run Code
using System;

class Program {
    static void Main() {
        Console.Write("For loop: ");
        for (int i = 1; i <= 5; i++) {
            Console.Write(i + " ");
        }
        Console.WriteLine();

        // While loop with continue/break
        Console.Write("While sequence (skipping 3, breaking at 6): ");
        int count = 1;
        while (count <= 10) {
            if (count == 3) {
                count++;
                continue; // Skip the rest of this loop iteration
            }
            if (count == 6) {
                break; // Exit the loop entirely
            }
            Console.Write(count + " ");
            count++;
        }
        Console.WriteLine();
    }
}
3 Code Challenge
Challenge: Write a loop that sums all odd numbers between 1 and 30. Skip the number 13 using the `continue` keyword, and print the computed sum at the end.