Paramclasses Academy - Blog

Tutorials Details

←
Post 8 of 30
→

What is C# Loops Explained: For, Foreach, While and Do-While ?

What is C# Loops Explained: For, Foreach, While and Do-While ?

October 24, 2026

Introduction

Loops are one of the most important concepts in C# programming. They allow developers to execute a block of code repeatedly without writing the same statements multiple times.

For example, suppose you want to print numbers from 1 to 100. Without a loop, you would need to write 100 print statements. With a loop, you can accomplish the same task in just a few lines of code.

C# provides four primary looping statements:

  • for loop

  • foreach loop

  • while loop

  • do-while loop

In this tutorial, you will learn how each loop works, when to use it, how to control loop execution, and how to apply loops in practical C# programs.

1. What Is a Loop in C#?

A loop is a control-flow statement that repeatedly executes a block of code while a specified condition is satisfied or while elements remain in a collection.

Consider this example without a loop:

Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
Console.WriteLine(4);
Console.WriteLine(5);

The same result can be achieved using a for loop:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

Output:

1
2
3
4
5

Loops make programs shorter, easier to maintain, and more efficient to develop.

2. The for Loop in C#

The for loop is commonly used when you know how many times a block of code should execute or when you need precise control over a counter.

Syntax

for (initialization; condition; iteration)
{
    // Code to execute repeatedly
}

The three parts have specific purposes:

  1. Initialization: Creates or initializes the loop variable.

  2. Condition: Determines whether the loop should continue.

  3. Iteration: Updates the loop variable after each iteration.

Example 1: Print Numbers from 1 to 10

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine(i);
}

Output:

1
2
3
4
5
6
7
8
9
10

How it works:

  • int i = 1 initializes the counter.

  • i <= 10 checks whether the counter is within the required range.

  • i++ increases the counter by one after each iteration.

  • When i becomes 11, the condition is false and the loop stops.

Example 2: Print Even Numbers

for (int i = 2; i <= 20; i += 2)
{
    Console.WriteLine(i);
}

This loop prints even numbers from 2 to 20.

Example 3: Calculate the Sum of Numbers

int sum = 0;

for (int i = 1; i <= 10; i++)
{
    sum += i;
}

Console.WriteLine($"Sum = {sum}");

Output:

Sum = 55

The variable sum accumulates each number from 1 to 10.

Example 4: Print a Multiplication Table

int number = 5;

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine($"{number} x {i} = {number * i}");
}

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Use a for loop when you need a counter, a numeric range, or a predictable number of iterations.

3. The foreach Loop in C#

The foreach loop is designed to iterate through the elements of a collection, such as an array or a list.

Instead of managing an index manually, foreach provides each element one at a time.

Syntax

foreach (type item in collection)
{
    // Code to execute for each item
}

Example 1: Iterate Through an Array

string[] fruits = { "Apple", "Banana", "Mango", "Orange" };

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Output:

Apple
Banana
Mango
Orange

In each iteration, the variable fruit represents the current array element.

Example 2: Calculate the Total of Array Elements

int[] numbers = { 10, 20, 30, 40, 50 };
int total = 0;

foreach (int number in numbers)
{
    total += number;
}

Console.WriteLine($"Total = {total}");

Output:

Total = 150

Example 3: Display Student Names

string[] students =
{
    "Rahul",
    "Priya",
    "Amit",
    "Neha"
};

foreach (string student in students)
{
    Console.WriteLine($"Student: {student}");
}

Output:

Student: Rahul
Student: Priya
Student: Amit
Student: Neha

for vs foreach

A for loop provides direct access to the loop index, while foreach focuses on visiting each element.

Use for when you need an index or want to control which positions are processed. Use foreach when you want to process each element in a collection.

A foreach iteration variable is not an index and generally should not be reassigned to change the underlying collection element. To update elements in an array, a for loop is often appropriate.

4. The while Loop in C#

The while loop executes a block of code as long as its condition evaluates to true.

The condition is checked before each iteration. Therefore, the loop body might never execute if the condition is initially false.

Syntax

while (condition)
{
    // Code to execute repeatedly
}

Example 1: Print Numbers from 1 to 5

int i = 1;

while (i <= 5)
{
    Console.WriteLine(i);
    i++;
}

Output:

1
2
3
4
5

The counter is initialized before the loop and incremented inside its body.

Example 2: Countdown

int countdown = 5;

while (countdown > 0)
{
    Console.WriteLine(countdown);
    countdown--;
}

Console.WriteLine("Go!");

Output:

5
4
3
2
1
Go!

Example 3: Read Input Until the User Enters Exit

string? input;

while (true)
{
    Console.Write("Enter a command (type exit to stop): ");
    input = Console.ReadLine();

    if (string.Equals(input, "exit",
        StringComparison.OrdinalIgnoreCase))
    {
        break;
    }

    Console.WriteLine($"You entered: {input}");
}

This example demonstrates a loop that continues until the user provides a stopping command. The break statement exits the loop.

Use while when the number of iterations is not known in advance and depends on a condition, user input, or changing program state.

5. The do-while Loop in C#

The do-while loop is similar to the while loop, but it checks the condition after executing the loop body.

This means that the body always executes at least once.

Syntax

do
{
    // Code to execute
}
while (condition);

Notice the semicolon after the while condition.

Example 1: Print Numbers from 1 to 5

int i = 1;

do
{
    Console.WriteLine(i);
    i++;
}
while (i <= 5);

Output:

1
2
3
4
5

Example 2: Execute the Loop at Least Once

int number = 10;

do
{
    Console.WriteLine(number);
}
while (number < 5);

Output:

10

Even though number < 5 is false, the message is printed once because the condition is evaluated after the loop body.

Example 3: Simple Menu Program

int choice;

do
{
    Console.WriteLine("\n--- Main Menu ---");
    Console.WriteLine("1. View Profile");
    Console.WriteLine("2. Settings");
    Console.WriteLine("3. Exit");
    Console.Write("Enter your choice: ");

    string? input = Console.ReadLine();

    if (!int.TryParse(input, out choice))
    {
        choice = 0;
    }

    switch (choice)
    {
        case 1:
            Console.WriteLine("Opening profile...");
            break;

        case 2:
            Console.WriteLine("Opening settings...");
            break;

        case 3:
            Console.WriteLine("Exiting application...");
            break;

        default:
            Console.WriteLine("Invalid choice. Try again.");
            break;
    }
}
while (choice != 3);

This program repeatedly displays a menu until the user selects option 3. Invalid numeric input is handled by assigning 0 to the choice.

Use do-while when an operation must happen at least once, such as displaying a menu or prompting for input.

6. Difference Between for, foreach, while and do-while

Feature for foreach while do-while
Best suited for Counter-based repetition Iterating through collections Condition-based repetition Repetition that must happen at least once
Condition checked Before each iteration Collection determines iteration Before each iteration After each iteration
May execute zero times Yes Yes, for an empty collection Yes No
Manual counter often needed Yes No Often Often
Index available directly Yes No, not by default If maintained If maintained

There is no universally best loop. Choose the loop that makes the intended behavior clearest.

7. Nested Loops in C#

A nested loop is a loop placed inside another loop. The inner loop runs for each iteration of the outer loop, subject to its own condition.

Example: Print a Rectangle Pattern

for (int row = 1; row <= 3; row++)
{
    for (int column = 1; column <= 4; column++)
    {
        Console.Write("* ");
    }

    Console.WriteLine();
}

Output:

* * * *
* * * *
* * * *

The outer loop controls the rows, while the inner loop controls the columns.

Example: Multiplication Grid

for (int row = 1; row <= 3; row++)
{
    for (int column = 1; column <= 3; column++)
    {
        Console.Write($"{row * column,4}");
    }

    Console.WriteLine();
}

Output:

   1   2   3
   2   4   6
   3   6   9

Nested loops are useful for working with grids, tables, matrices, and combinations of values. Keep in mind that nested loops can increase execution time significantly as the number of iterations grows.

8. The break Statement

The break statement immediately terminates the nearest enclosing loop or exits a switch statement.

Example

for (int i = 1; i <= 10; i++)
{
    if (i == 6)
    {
        break;
    }

    Console.WriteLine(i);
}

Output:

1
2
3
4
5

When i becomes 6, the loop terminates without printing 6.

Use break when the desired result has been found or a stopping condition has occurred.

9. The continue Statement

The continue statement skips the remainder of the current iteration and moves to the next iteration.

Example: Print Odd Numbers

for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0)
    {
        continue;
    }

    Console.WriteLine(i);
}

Output:

1
3
5
7
9

When the number is even, continue skips the print statement.

Remember: break exits the loop, while continue skips only the current iteration.

10. Infinite Loops in C#

An infinite loop continues indefinitely unless something inside it terminates the loop or the program itself stops.

Example

while (true)
{
    Console.WriteLine("Running...");
}

This loop continues printing until the process is interrupted or the program exits.

Infinite loops can be intentional in servers, event-processing systems, and applications that continuously monitor activity. However, they must have an appropriate exit mechanism when required.

A common mistake is forgetting to update the loop variable:

int i = 1;

while (i <= 5)
{
    Console.WriteLine(i);
    // Missing i++ causes an infinite loop.
}

To fix the problem:

int i = 1;

while (i <= 5)
{
    Console.WriteLine(i);
    i++;
}

Always check whether the loop condition can eventually become false.

11. Practical Project: Student Marks Analyzer

Let's combine loops and conditional statements in a practical console program that calculates the total, average, highest mark, lowest mark, and number of passing students.

int[] marks = { 85, 72, 39, 91, 64 };

int total = 0;
int highest = marks[0];
int lowest = marks[0];
int passingStudents = 0;

foreach (int mark in marks)
{
    total += mark;

    if (mark > highest)
    {
        highest = mark;
    }

    if (mark < lowest)
    {
        lowest = mark;
    }

    if (mark >= 40)
    {
        passingStudents++;
    }
}

double average = (double)total / marks.Length;

Console.WriteLine($"Total Marks: {total}");
Console.WriteLine($"Average Marks: {average:F2}");
Console.WriteLine($"Highest Marks: {highest}");
Console.WriteLine($"Lowest Marks: {lowest}");
Console.WriteLine($"Passing Students: {passingStudents}");

Output:

Total Marks: 351
Average Marks: 70.20
Highest Marks: 91
Lowest Marks: 39
Passing Students: 4

What does this program demonstrate?

  • foreach processes each mark in the array.

  • total += mark calculates the sum.

  • if statements update the highest and lowest values.

  • The passing-student counter increases when a mark is at least 40.

  • Casting total to double ensures the average can include a fractional part.

  • F2 formats the average to two decimal places.

This example demonstrates how loops, arrays, variables, and conditional statements work together in a real program.

12. Common Mistakes When Using Loops

Mistake 1: Off-by-One Errors

for (int i = 1; i < 5; i++)
{
    Console.WriteLine(i);
}

This prints 1 through 4, not 1 through 5.

To include 5, use i <= 5.

Mistake 2: Forgetting to Update the Counter

A while loop may run indefinitely if its condition never becomes false.

Make sure the loop body or another part of the program updates the relevant state.

Mistake 3: Using the Wrong Loop

Using a manually indexed loop when you only need to process every collection element can add unnecessary complexity. Prefer foreach when the index is not needed.

Mistake 4: Adding a Semicolon Incorrectly

while (i < 5); // Usually unintended
{
    Console.WriteLine(i);
    i++;
}

The semicolon creates an empty loop body. The following block is separate from the loop and does not behave as intended.

Mistake 5: Modifying a Collection During foreach

Adding or removing elements from many collections during a foreach iteration invalidates the enumerator and can throw an InvalidOperationException.

If you need to change elements, use an appropriate indexed loop or a collection-specific approach. When removing items, consider iterating backward through an index-based collection or building a separate result collection.

13. Best Practices for Using Loops

  • Choose the loop that most clearly communicates your intent.

  • Use meaningful variable names such as index, student, or count.

  • Ensure condition-based loops have a clear termination strategy.

  • Avoid unnecessary nested loops when a simpler approach is available.

  • Use foreach for straightforward collection traversal.

  • Use for when the index or iteration step matters.

  • Keep loop bodies focused and easy to read.

  • Test empty collections, boundary values, and unexpected input.

  • Avoid repeatedly calculating expensive values inside a loop when they can safely be calculated beforehand.

  • Use break and continue when they make the logic clearer, not as substitutes for understandable structure.

14. Practice Exercise

Build a C# console program that prints the multiplication table for a number entered by the user.

Requirements:

  1. Ask the user to enter an integer.

  2. Validate the input using int.TryParse.

  3. Use a for loop to print the table from 1 to 10.

  4. Display each result in the format number x multiplier = result.

  5. Print an appropriate message if the input is invalid.

Bonus challenge: Modify the program to let the user generate multiple multiplication tables until they choose to exit.

Try implementing the program yourself before looking for a solution. This will help you understand loop initialization, conditions, iteration, and input validation.

15. Frequently Asked Questions

Q1. How many types of loops are available in C#?

C# provides four primary loop statements: for, foreach, while, and do-while.

Q2. What is the difference between while and do-while?

A while loop checks its condition before executing the body and may execute zero times. A do-while loop checks the condition afterward, so its body executes at least once.

Q3. When should I use foreach instead of for?

Use foreach when you need to process each element in a collection and do not need to manage an index. Use for when you need index-based access or precise counter control.

Q4. What is the difference between break and continue?

break terminates the nearest enclosing loop. continue skips the remaining statements in the current iteration and proceeds to the next iteration.

Q5. Can loops be nested in C#?

Yes. You can place one loop inside another to process grids, matrices, tables, and other multidimensional structures.

Q6. What causes an infinite loop?

An infinite loop can occur when its termination condition never becomes false, often because a counter is not updated or the condition is incorrect.

Q7. Are loops important in real-world C# development?

Yes. Loops are used for processing collections, reading data, generating reports, validating input, performing calculations, and many other repetitive tasks.

16. Quick Knowledge Check

Question 1: Which loop is guaranteed to execute its body at least once?

A. for

B. foreach

C. while

D. do-while

Question 2: Which statement immediately exits a loop?

A. skip

B. break

C. continue

D. next

Question 3: Which loop is generally most convenient for processing every item in an array without needing an index?

A. foreach

B. while

C. do-while

D. switch

Question 4: What happens when a while condition is false before the first iteration?

A. The body executes once.

B. The loop executes twice.

C. The body does not execute.

D. The program always crashes.

Answers: 1 — D, 2 — B, 3 — A, 4 — C.

Conclusion

C# loops are essential tools for writing concise, maintainable programs. The for loop is useful for counter-based repetition, foreach simplifies collection traversal, while handles condition-based repetition, and do-while guarantees at least one execution.

Understanding nested loops, break, continue, and loop termination will help you write more reliable programs and prepare you for arrays, collections, algorithms, and practical .NET development.

Practice each loop with small programs, test boundary conditions, and focus on writing code that is easy to understand and maintain.

←
Post 8 of 30
→