C# - Loops
In C#, loops are used to execute a block of code repeatedly until a specified condition is met. They are essential for performing repetitive tasks efficiently. C# provides several types of loops, each suited for different scenarios. Here’s an overview of the most commonly used loops in C#:
1. for Loop
The for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and iteration.
Syntax:
csharpfor (initialization; condition; iteration)
{
// Code to execute
}
Example:
csharpfor (int i = 0; i < 5; i++)
{
Console.WriteLine(i); // Prints numbers 0 to 4
}
2. while Loop
The while loop executes a block of code as long as the specified condition is true. The condition is checked before the execution of the loop body.
Syntax:
csharpwhile (condition)
{
// Code to execute
}
Example:
csharpint i = 0;
while (i < 5)
{
Console.WriteLine(i); // Prints numbers 0 to 4
i++;
}
3. do-while Loop
The do-while loop is similar to the while loop but guarantees that the code block will execute at least once, as the condition is checked after the loop body.
Syntax:
csharpdo
{
// Code to execute
} while (condition);
Example:
csharpint i = 0;
do
{
Console.WriteLine(i); // Prints numbers 0 to 4
i++;
} while (i < 5);
4. foreach Loop
The foreach loop is used to iterate over elements in a collection, such as arrays or lists. It is ideal when you need to access each item in a collection without needing to know the index.
Syntax:
csharpforeach (var item in collection)
{
// Code to execute
}
Example:
csharpstring[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
{
Console.WriteLine(name); // Prints each name in the array
}
5. break Statement
The break statement is used to exit a loop prematurely, regardless of the loop condition.
Example:
csharpfor (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop when i is 5
}
Console.WriteLine(i); // Prints numbers 0 to 4
}
6. continue Statement
The continue statement skips the remaining code in the current iteration of the loop and proceeds to the next iteration.
Example:
csharpfor (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip even numbers
}
Console.WriteLine(i); // Prints odd numbers from 1 to 9
}
7. Nested Loops
You can nest loops within each other to perform more complex iterations.
Example:
csharpfor (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine($"i = {i}, j = {j}");
}
}
8. Using Loops with Collections
Loops are often used to iterate over collections such as arrays, lists, or dictionaries.
Example with Array:
csharpint[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number); // Prints numbers 1 to 5
}
Example with List:
csharpList<string> cities = new List<string> { "New York", "London", "Tokyo" };
foreach (string city in cities)
{
{
Console.WriteLine(city); // Prints each city in the list
}
Example with Dictionary:
csharpDictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 },
{ "Charlie", 35 }
};
foreach (KeyValuePair<string, int> entry in ages)
{
Console.WriteLine($"{entry.Key}: {entry.Value}"); // Prints name and age
}
Summary
Loops in C# are powerful constructs for executing code repeatedly. The for loop is ideal for scenarios with a known number of iterations, while the while and do-while loops are useful when the number of iterations is not known in advance. The foreach loop simplifies iterating over collections. Understanding how to use break and continue statements effectively can help control loop execution. Nested loops and loop operations with collections further enhance the versatility of loops in C#.