Loops

Intermediate 20 min read Lesson 6 of 13

What are Loops?

Loops let you repeat code multiple times. Think of them like a washing machine cycle - you set it to repeat the same action until the clothes are clean.

for
Known count

while
Unknown count

do-while
Run at least once

foreach
For collections

Think of it like this: Imagine you have 10 boxes to paint. Instead of painting one at a time with 10 separate instructions, you tell the computer: "Repeat this painting action 10 times." That's a loop!

The for Loop

The for loop is used when you know exactly how many times you want to repeat something. It has three parts:

Start

Where to begin

int i = 0
Condition

When to stop

i < 10
Update

How to step forward

i++
// ===== BASIC FOR LOOP =====
// for (start; condition; update)
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Number: {i}");  // Prints 1,2,3,4,5
}

// ===== COUNTING DOWN =====
for (int i = 5; i >= 1; i--)
{
    Console.WriteLine($"Countdown: {i}");  // Prints 5,4,3,2,1
}

// ===== REAL-WORLD EXAMPLE: Print even numbers up to 20
for (int i = 0; i <= 20; i += 2)
{
    Console.WriteLine($"Even number: {i}");
}

// ===== REAL-WORLD EXAMPLE: Process a list of items
for (int i = 0; i < items.Count; i++)
{
    Console.WriteLine($"Processing item {i}: {items[i]}");
}
When to use for: When you know exactly how many times to loop, or when you need the index number.

The while Loop

The while loop keeps running as long as a condition is true. It checks the condition before each run. If the condition is false from the start, the loop never runs.

When to use while
  • You don't know how many times to loop
  • Loop depends on user input
  • Loop depends on changing data
  • Reading from a file until end
Important!
  • Make sure the condition eventually becomes false
  • Otherwise, you get an infinite loop
  • Always update the variable in the condition
// ===== BASIC WHILE LOOP =====
int count = 0;
while (count < 5)
{
    Console.WriteLine($"Count: {count}");
    count++;  // IMPORTANT: Update the variable!
}

// ===== REAL-WORLD EXAMPLE: Password validation
string password = "";
while (password != "secret")
{
    Console.Write("Enter password: ");
    password = Console.ReadLine();
    if (password != "secret")
    {
        Console.WriteLine("Wrong password, try again!");
    }
}
Console.WriteLine("Access granted!");

// ===== REAL-WORLD EXAMPLE: Sum numbers until user enters 0
int sum = 0;
int number = 1;
while (number != 0)
{
    Console.Write("Enter a number (0 to stop): ");
    number = int.Parse(Console.ReadLine());
    sum += number;
}
Console.WriteLine($"Total sum: {sum}");
Warning: Forgetting to update the variable in a while loop creates an infinite loop that never stops!

The do-while Loop

The do-while loop is like a while loop, but it checks the condition after the code runs. This means the code always runs at least once.

When to use do-while
  • When you need to do something at least once
  • Menu systems (show menu first)
  • Getting valid user input
  • Games with "play again?" prompts
Key Difference

while checks first, then runs.
do-while runs first, then checks.

// ===== BASIC DO-WHILE =====
int number;
do
{
    Console.Write("Enter a number (0 to quit): ");
    number = int.Parse(Console.ReadLine());
    Console.WriteLine($"You entered: {number}");
} while (number != 0);

// ===== REAL-WORLD EXAMPLE: Simple Menu System
int choice;
do
{
    Console.WriteLine("\n--- MENU ---");
    Console.WriteLine("1. Say Hello");
    Console.WriteLine("2. Say Goodbye");
    Console.WriteLine("3. Exit");
    Console.Write("Choose an option: ");
    choice = int.Parse(Console.ReadLine());

    switch (choice)
    {
        case 1:
            Console.WriteLine("Hello, World!");
            break;
        case 2:
            Console.WriteLine("Goodbye!");
            break;
        case 3:
            Console.WriteLine("Exiting...");
            break;
        default:
            Console.WriteLine("Invalid choice!");
            break;
    }
} while (choice != 3);
Remember: Do-while is perfect for menus and situations where the user must see the options at least once.

The foreach Loop

The foreach loop is designed for collections like arrays, lists, and other groups of items. It goes through each item one by one.

Benefits
  • Clean and readable
  • No need for index variables
  • Works with any collection
  • Cannot go out of bounds
Limitations
  • Cannot modify the collection while looping
  • No access to index (use for loop if needed)
  • Read-only by nature
// ===== BASIC FOREACH =====
string[] names = { "Alice", "Bob", "Charlie" };

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

// ===== WITH NUMBERS =====
int[] scores = { 95, 88, 76, 92 };
int total = 0;
foreach (int score in scores)
{
    total += score;
}
Console.WriteLine($"Total: {total}, Average: {total / scores.Length}");

// ===== WITH INDEX (Using a counter) =====
int index = 0;
foreach (string name in names)
{
    Console.WriteLine($"{index}: {name}");
    index++;
}

// ===== REAL-WORLD EXAMPLE: Process order items
var orderItems = new List<string> { "Pizza", "Soda", "Salad" };
foreach (string item in orderItems)
{
    Console.WriteLine($"Adding {item} to your order...");
}
Pro Tip: Use foreach whenever you just need to read items from a collection. It's cleaner and safer than a for loop.

Loop Control Statements

These special keywords let you control how your loop behaves.

break

Exits the loop immediately

if (i == 5) break;
continue

Skips the current iteration

if (i == 3) continue;
// ===== BREAK - Exit the loop =====
for (int i = 1; i <= 10; i++)
{
    if (i == 5)
        break;  // Stops when i reaches 5
    Console.WriteLine($"i = {i}");  // Prints: 1,2,3,4
}

// ===== CONTINUE - Skip this iteration =====
for (int i = 1; i <= 5; i++)
{
    if (i == 3)
        continue;  // Skips when i is 3
    Console.WriteLine($"i = {i}");  // Prints: 1,2,4,5
}

// ===== REAL-WORLD EXAMPLE: Find first matching item
string[] fruits = { "apple", "banana", "cherry", "date" };
string searchFor = "cherry";

for (int i = 0; i < fruits.Length; i++)
{
    if (fruits[i] == searchFor)
    {
        Console.WriteLine($"Found {searchFor} at index {i}");
        break;  // Stop searching once found
    }
}

Which Loop to Use?

Loop When to Use Example Scenario
for You know the exact count Processing 10 students
while You don't know the count Waiting for correct password
do-while Must run at least once Showing a menu to the user
foreach Reading from a collection Displaying all items in a list

Exercise: Number Guessing Game

Task: Create a number guessing game using loops.

Instructions:
  1. Create a console application called "GuessingGame"
  2. Generate a random number between 1 and 100
  3. Use a while loop to let the user keep guessing
  4. Give hints: "Too high" or "Too low"
  5. Count how many attempts the user takes
  6. When they guess correctly, display the number of attempts
  7. Use do-while to ask if they want to play again
  8. Use break to exit when they guess correctly
Hints:
  • Use Random random = new Random(); to create a random number
  • Use random.Next(1, 101) to get a number between 1 and 100
  • Use int.Parse(Console.ReadLine()) to get the user's guess
  • Keep a counter: int attempts = 0;
  • In the do-while, ask: "Play again? (y/n)"
Expected Output:
Guess the number (1-100): 50
Too low!
Guess the number (1-100): 75
Too high!
Guess the number (1-100): 63
Too low!
Guess the number (1-100): 68
Congratulations! You found it in 4 attempts!
Play again? (y/n): n
Thanks for playing!
Key Takeaway

Loops let you repeat code efficiently. Choose the right loop for your situation:

for → When you know the count
while → When you don't know the count
do-while → When you need to run at least once
foreach → When working with collections

Test Your Knowledge - Take Quiz