In C#, loops are used to execute a block of code repeatedly as long as a specified condition is satisfied. Loops help reduce code duplication and improve efficiency.
C# provides different types of loops depending on how and when the condition is evaluated.
The for loop is used when the number of iterations is known in advance.
for (initialization; condition; increment/decrement)
{
// code to be executed
}
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
Use Case: Iterating over arrays, fixed-range loops
The while loop executes a block of code as long as the condition remains true. The condition is checked before execution.
while (condition)
{
// code to be executed
}
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
Note: If the condition is false initially, the loop will not execute even once.
The do-while loop executes the code block at least once before checking the condition.
do
{
// code to be executed
}
while (condition);
int i = 1;
do
{
Console.WriteLine(i);
i++;
}
while (i <= 5);
Even if the condition is false initially, the loop runs once.
The foreach loop is used to iterate through elements of a collection such as arrays, lists, or other enumerable objects.
It is especially useful when you do not need the index and only want to access each element.
foreach (datatype variable in collection)
{
// code to be executed
}
string[] fruits = { "Apple", "Banana", "Mango" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Use Case: Iterating through arrays, lists, and collections without modifying them.
Note: You cannot modify the collection elements
directly inside a foreach loop.
| Loop | Condition Check | Minimum Execution |
|---|---|---|
| for | Before loop | 0 times |
| while | Before loop | 0 times |
| do-while | After loop | 1 time |
| foreach | Handled internally | 0 times |
Loops are essential for efficient programming in C#. Choosing the correct loop type improves performance and readability.