Skip to main content
C# Fundamentals for Beginners to Advanced
CHAPTER 08 Beginner

Loops in C#

Updated: May 17, 2026
5 min read

# CHAPTER 8

Loops in C#

1. Introduction

Imagine needing to send an email to 10,000 registered users. Writing the send command 10,000 times manually is impossible. Loops solve this by allowing a block of code to run repeatedly as long as a specified condition remains true. They are the backbone of automation in programming.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use the for loop for iteration.
  • Use the while loop for unknown iteration counts.
  • Use the do-while loop for guaranteed first execution.
  • Use the foreach loop to iterate over collections.
  • Manipulate loop flow using break and continue.

3. The for Loop

Used when you know exactly how many times you want the loop to run.

Syntax: for (initialization; condition; increment/decrement)

csharp
12345678910111213141516
using System;

namespace LoopsApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Prints numbers 1 to 5
            for (int i = 1; i <= 5; i++) 
            {
                Console.WriteLine($"Count: {i}");
            }
        }
    }
}

How it works:

  1. 1. int i = 1: Executes ONCE at the start.
  1. 2. i <= 5: Checked before every loop. If true, run the code. If false, stop.
  1. 3. i++: Executes after the code block runs, then goes back to step 2.

4. The while Loop

Used when you don't know how many times the loop will run, but you know the condition that should keep it running.
csharp
1234567
int count = 1;

while (count <= 3) 
{
    Console.WriteLine("Hello!");
    count++; // CRITICAL: Don't forget to update the condition!
}

5. The do-while Loop

Similar to the while loop, but it guarantees that the code block will execute at least once, because the condition is checked at the *bottom* of the loop.
csharp
12345678910
int password;

do 
{
    Console.Write("Enter PIN (1234): ");
    password = int.Parse(Console.ReadLine());
    
} while (password != 1234); // Keeps looping until correct

Console.WriteLine("Access Granted!");

6. The foreach Loop

The most widely used loop in modern C#. It is explicitly designed to iterate through arrays, lists, and collections cleanly and safely. It prevents "out of bounds" errors automatically.
csharp
1234567
string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };

// Automatically grabs each item, one by one
foreach (string car in cars) 
{
    Console.WriteLine(car);
}

7. The break and continue Statements

  • break: Immediately terminates the loop completely.
  • continue: Skips the rest of the current iteration and jumps to the next one.
csharp
12345678910111213
for (int i = 1; i <= 10; i++) 
{
    if (i == 4) 
    {
        continue; // Skips printing 4
    }
    if (i == 8) 
    {
        break; // Stops the loop entirely at 8
    }
    Console.Write(i + " ");
}
// Output: 1 2 3 5 6 7

8. Mini Project: Number Guessing Game

csharp
123456789101112131415161718192021222324252627282930
using System;

namespace GuessingGame
{
    class Program
    {
        static void Main(string[] args)
        {
            int secretNum = 7;
            int guess = 0;
            int attempts = 0;

            Console.WriteLine("Guess the secret number (1-10)!");

            while (guess != secretNum) 
            {
                Console.Write("Enter guess: ");
                guess = int.Parse(Console.ReadLine());
                attempts++;

                if (guess != secretNum) 
                {
                    Console.WriteLine("Wrong, try again.");
                }
            }

            Console.WriteLine($"You win! It took you {attempts} attempts.");
        }
    }
}

9. Common Mistakes

  • Infinite Loops: Forgetting count++ in a while loop means the condition never becomes false. The program will freeze and consume 100% of a CPU core until you force quit it.
  • Off-by-One Errors: Using < 5 instead of <= 5 when you actually want it to run 5 times starting from 1.

10. Best Practices

  • Prefer foreach over for when iterating through collections. It makes your intent clearer and eliminates the risk of indexing errors.
  • Always initialize your variables outside of while loops if you need to use their final values after the loop ends.

11. Exercises

  1. 1. Write a for loop that prints all even numbers from 2 to 20.
  1. 2. Write a while loop that creates a countdown timer from 10 to 1, then prints "Liftoff!".

12. MCQs with Answers

Question 1

Which loop is best when you know exactly how many iterations you need?

Question 2

Which loop guarantees the code block will execute at least once?

Question 3

Which loop is specifically designed to safely iterate through arrays and collections?

Question 4

What does the break statement do?

Question 5

What does the continue statement do?

Question 6

What causes an infinite loop?

Question 7

What is the output of for(int i=0; i<3; i++) Console.Write(i);?

Q8. Can you use the var keyword inside a foreach loop declaration? a) Yes (e.g., foreach(var item in list)) b) No Answer: a) Yes
Question 9

Which loop checks its condition at the bottom?

Q10. Can you put a loop inside another loop? a) Yes, this is called a nested loop b) No, the compiler prevents it Answer: a) Yes, this is called a nested loop

13. Interview Questions

  • Q: Explain the difference between a while loop and a do-while loop. Provide a scenario for each.
  • Q: Why is foreach generally preferred over a standard for loop when dealing with List<T>?

14. Summary

Loops execute code repeatedly. The for loop is ideal for known iteration counts. The while loop handles conditional repetition. The do-while loop ensures at least one execution. foreach is the modern standard for processing collections. break and continue give fine-grained control over execution flow.

15. Next Chapter Recommendation

In Chapter 9: Arrays and Collections, we will learn how to store large amounts of data in a single variable, making heavy use of the foreach loop you just learned.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·