C# loops
In C#, loops are used to execute a block of code repeatedly as long as a specified condition is true. Loops help reduce code duplication and allow you to handle repetitive tasks efficiently.
Types of Loops in C#
for
loopforeach
loopwhile
loopdo-while
loop
Each type of loop has its own use cases depending on the situation and the type of iteration you need.
1. for
Loop
The for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
Syntax of for
Loop:
for (initialization; condition; increment/decrement)
{
// Code to be executed
}
initialization
: Initializes the loop control variable (e.g.,int i = 0
).condition
: The loop continues as long as this condition is true.increment/decrement
: Updates the loop control variable after each iteration.
Example:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Iteration: " + i);
}
This loop will print the following output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
2. foreach
Loop
The foreach
loop is used to iterate over elements in a collection (such as arrays, lists, or other collections) without needing to manage the loop index manually. It simplifies iterating through collections.
Syntax of foreach
Loop:
foreach (dataType item in collection)
{
// Code to execute for each element
}
dataType item
: The type of the variable that will represent each item in the collection.collection
: The collection you are iterating through (e.g., array, list).
Example:
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
This loop will print the following output:
Apple Banana Cherry
3. while
Loop
The while
loop executes a block of code as long as the specified condition is true. If the condition is false from the start, the loop does not execute at all.
Syntax of while
Loop:
while (condition)
{
// Code to execute while condition is true
}
condition
: The loop continues as long as this condition is true.
Example:
int i = 1;
while (i <= 5)
{
Console.WriteLine("Count: " + i);
i++;
}
This loop will print:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
4. do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code block will execute at least once, even if the condition is false, because the condition is checked after executing the loop body.
Syntax of do-while
Loop:
do
{
// Code to execute
} while (condition);
condition
: The loop continues as long as this condition is true.
Example:
int i = 1;
do
{
Console.WriteLine("Count: " + i);
i++;
} while (i <= 5);
This loop will also print:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
5. Loop Control Statements
C# provides the following statements to control loop behavior:
break
: Terminates the loop and transfers control to the statement immediately following the loop.for (int i = 1; i <= 5; i++) { if (i == 3) { break; // Loop stops when i equals 3 } Console.WriteLine(i); }
Output:
1 2
continue
: Skips the current iteration of the loop and moves to the next iteration.for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip the iteration when i equals 3 } Console.WriteLine(i); }
Output:
1 2 4 5
When to Use Each Loop
for
loop: When you know the number of iterations ahead of time (e.g., iterating a fixed number of times).foreach
loop: When iterating through a collection (like arrays, lists) without needing an index.while
loop: When you don't know the number of iterations in advance and the loop depends on a condition.do-while
loop: When you want the loop to execute at least once, regardless of the condition.
6. Infinite Loops
An infinite loop occurs when the condition in the loop is always true. For example:
while (true)
{
// This will run forever
Console.WriteLine("This is an infinite loop.");
}
Make sure to avoid infinite loops unless that's the intended behavior, such as in certain background services or event polling mechanisms.
Summary
- C# provides four types of loops:
for
,foreach
,while
, anddo-while
, each suited for different types of iteration needs. - You can use
break
to exit a loop early orcontinue
to skip the current iteration and move to the next one. - Choose the appropriate loop based on the structure and requirements of your iteration, whether you are working with a known range, a collection, or an indeterminate condition.