Loops in C#
Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. C# provides several types of loops, each suited for different scenarios.
The for
Loop
The for
loop is typically used when you know in advance how many times you want to iterate. It consists of three parts: initialization, condition, and iterator.
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Iteration number: {i}");
}
In this example, the loop initializes a counter variable i
to 0. It continues to execute as long as i
is less than 5. After each iteration, i
is incremented by 1.
The while
Loop
The while
loop executes a block of code as long as a specified condition is true. It's useful when the number of iterations is not known beforehand.
int count = 0;
while (count < 3)
{
Console.WriteLine($"Count is: {count}");
count++;
}
The loop checks the condition count < 3
before each iteration. If the condition is true, the code inside the loop is executed, and count
is incremented. If the condition becomes false, the loop terminates.
The do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code block is executed at least once before the condition is checked.
int j = 0;
do
{
Console.WriteLine($"Value of j: {j}");
j++;
} while (j < 2);
Even if the condition j < 2
were initially false, the code inside the do
block would still execute once.
The foreach
Loop
The foreach
loop is used to iterate over elements in a collection (like arrays or lists) without needing to manage an index.
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
This loop iterates through each fruit
in the fruits
collection.
Loop Control Statements
C# also provides statements to control the flow of loops:
break
: Exits the loop immediately.continue
: Skips the rest of the current iteration and proceeds to the next one.
for (int k = 0; k < 10; k++)
{
if (k == 5)
{
continue; // Skip iteration when k is 5
}
if (k == 8)
{
break; // Exit loop when k is 8
}
Console.WriteLine(k);
}
Understanding and utilizing loops effectively is crucial for writing dynamic and efficient C# applications.