articles

home / developersection / articles / understanding loops in c#

Understanding Loops in C#

Understanding Loops in C#

Anubhav Kumar 987 22-Apr-2025

Loops are fundamental in programming. They allow us to repeat a block of code multiple times, which is especially useful when dealing with repetitive tasks like processing arrays, running calculations, or displaying data.

In this article, we’ll explore the different types of loops in C#, including:

  • for
  • while
  • do...while
  • foreach

 

Why Use Loops?

Imagine printing numbers from 1 to 100 manually — it’s inefficient and error-prone. With loops, we can automate such tasks with just a few lines of code.

1. for Loop

The for loop is commonly used when the number of iterations is known ahead of time.

Syntax:

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

Example:

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

Output:

Count: 1  
Count: 2  
Count: 3  
Count: 4  
Count: 5  

2. while Loop

The while loop runs as long as the condition is true. It’s useful when you don’t know how many times the loop should run.

Syntax:

while (condition)
{
    // Code to execute
}

Example:

int i = 1;
while (i <= 5)
{
    Console.WriteLine("Number: " + i);
    i++;
}

3. do...while Loop

This loop is similar to while, but it executes the code block at least once, even if the condition is false.

Syntax:

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

Example:

int i = 1;
do
{
    Console.WriteLine("Value: " + i);
    i++;
}
while (i <= 5);

4. foreach Loop

The foreach loop is used to iterate over collections like arrays, lists, or any enumerable data.

Syntax:

foreach (datatype item in collection)
{
    // Code to execute
}

Example:

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

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

Output: 

Apple  
Banana  
Cherry  

Breaking and Continuing Loops

You can control loop execution using:

Keyword Description
break Exits the loop entirely
continue Skips the current iteration and moves to the next

Example with break:

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

Output:

1 2 3 4 5

Example with continue:

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

Output: 

1 2 4 5

 

Summary Table

Loop Type Best Used When...
for Number of iterations is known
while Loop until a condition becomes false
do...while Run at least once, then check condition
foreach Iterating over a collection (array/list)

c# c# 
Updated 22-Apr-2025
Anubhav Kumar

Student

The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By