Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Loops

What is a Loop?

A loop is a control flow statement that allows us to repeatedly execute a block of code until a specified condition is satisfied.

Loops are mainly used when the same operation needs to be performed multiple times. Instead of writing the same code again and again, we can use a loop to execute the code repeatedly.

Example: If you want to print numbers from 1 to 100, you do not need to write Console.WriteLine() 100 times. A loop can perform this task using only a few lines of code.

Types of Loops in C#

Loops are mainly divided into the following types:

Loop Purpose Best Used When
for Repeats code based on a counter Number of iterations is known
while Repeats code while a condition is true Number of iterations may not be known
do-while Executes the block at least once Code must execute at least one time
foreach Iterates through a collection Working with arrays or collections

1. For Loop

For Loop in C# is a control flow statement that allows us to repeatedly execute a block of code a specified number of times. The For Loop in C# is used when we know the exact number iterations. It contain three stages i.e. initialization, condition and increment or decrement operation.

The three parts of a for loop are:

  • Initialization: Runs only once when the loop begins. This is typically where you declare and set your loop counter variable.
  • Condition: A Boolean expression evaluated before every iteration. If true, the loop body runs; if false, the loop terminates.
  • Iterator: Executes at the end of every loop iteration, usually incrementing or decrementing the counter variable.

C# For Loop

Syntax
C#
for (initialization; condition; iterator)
{
    // Code to be executed
}
Example 1: Basic Incrementing Loop (Counting Up)

Write a program to print numbers from 1 to 10.

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

Output: 1 2 3 4 5 6 7 8 9 10

Example 2: Decrementing Loop (Counting Down)

A for loop can also be used to count backwards.

C#
using System;
 
for (int i = 10; i >= 1; i--)
{
    Console.WriteLine(i);
}

Output: 10 9 8 7 6 5 4 3 2 1

Example 3: Printing Even Numbers

We can use a loop with a condition to print only even numbers.

C#
using System;
 
for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0)
    {
        Console.WriteLine(i);
    }
}

Output: 2 4 6 8 10

2. While Loop

The while loop executes a block of code repeatedly as long as the specified condition evaluates to true.

The condition is checked before every iteration. If the condition is false initially, the loop body will not execute even once.

Syntax
C#
while (condition)
{
    // Code to be executed
}
Example
C#
using System;
 
int i = 1;

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

Output: 1 2 3 4 5

Important: Make sure the condition eventually becomes false. Otherwise, the while loop can become an infinite loop.

3. Do-While Loop

The do-while loop is similar to the while loop, but there is one important difference: the code block executes at least once before the condition is checked.

Syntax
C#
do
{
    // Code to be executed
}
while (condition);
Example
C#
using System;
 
int i = 1;
do
{
    Console.WriteLine(i);
    i++;
}
while (i <= 5);

Output: 1 2 3 4 5

Key Point: A do-while loop always executes its body at least once, even if the condition is initially false.

4. Foreach Loop

The foreach loop is used to iterate through each element of an array or collection. It is commonly used when we want to read every item without manually managing an index.

Syntax
C#
foreach (dataType variable in collection)
{
    // Code to be executed
}
Example
C#
using System;
 
string[] courses =
{
    "C#",
    ".NET",
    "SQL",
    "Azure"
};

foreach (string course in courses)
{
    Console.WriteLine(course);
}

The foreach loop automatically moves through every element of the collection one by one.

5. Nested Loops

A loop inside another loop is called a nested loop. The inner loop completes all of its iterations for every iteration of the outer loop.

Example: Pattern Printing
C#
using System;
 
for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        Console.Write("* ");
    }

    Console.WriteLine();
}

Output:

Output
* * *
* * *
* * *

6. Break Statement

The break statement is used to immediately terminate a loop. When the break statement is executed, control moves outside the loop.

Example
C#
using System;
 
for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        break;
    }

    Console.WriteLine(i);
}

Output: 1 2 3 4

7. Continue Statement

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

Example
C#
using System;
 
for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        continue;
    }

    Console.WriteLine(i);
}

Output: 1 2 4 5

For vs While vs Do-While vs Foreach

Feature for while do-while foreach
Condition Checked Before iteration Before iteration After iteration Automatically
Minimum Execution Zero times Zero times At least once Depends on collection
Best For Known iterations Unknown iterations Menu/input scenarios Collections

Real-World Example

Loops are widely used in real-world applications such as processing student records, displaying product lists, reading database records, generating reports, processing orders, and validating user input.

C#
using System;
 
string[] students =
{
    "Rahul",
    "Priya",
    "Amit",
    "Sneha"
};

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

Here, the foreach loop processes each student name one by one. Similar logic can be used to process records received from a database or API.

Common Mistakes to Avoid

  • Always make sure the loop condition can eventually become false.
  • Be careful with i++ and i-- to avoid unexpected results.
  • Avoid accidentally creating an infinite loop.
  • Use break when you need to terminate a loop early.
  • Use continue when you want to skip only the current iteration.
  • Use foreach when you simply need to process every item in a collection.
Summary

Loops are used to repeatedly execute a block of code. C# provides different types of loops such as for, while, do-while, and foreach. The for loop is useful when the number of iterations is known, while while and do-while are useful when execution depends on a condition. The foreach loop is commonly used with arrays and collections. Nested loops can be used for patterns and multi-dimensional data, while break and continue provide additional control over loop execution.

Practice Questions

  1. Write a program to print numbers from 1 to 100 using a for loop.
  2. Write a program to print numbers from 100 to 1 using a for loop.
  3. Write a program to print all even numbers between 1 and 50.
  4. Write a program to calculate the sum of numbers from 1 to 100.
  5. Write a program to print the multiplication table of a number.
  6. Write a program using while loop to print numbers from 1 to 10.
  7. Write a program using do-while loop for a simple menu.
  8. Create an array of five student names and display them using foreach.
  9. Create a nested loop to print a star pattern.
  10. Write a program using break and continue statements.