In C#, loops are used to execute a block of code repeatedly based on a condition. Here are the most common types of loops in C#:
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.
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Iteration: " + i);
}
{
Console.WriteLine("Iteration: " + i);
}
2. While Loop
The while
loop continues to execute as long as a specified condition is true.
int i = 0;
while (i < 10)
{
Console.WriteLine("Iteration: " + i);
i++;
}
while (i < 10)
{
Console.WriteLine("Iteration: " + i);
i++;
}
3. Do-While Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code block will be executed at least once.
int i = 0;
do
{
Console.WriteLine("Iteration: " + i);
i++;
}
while (i < 10);
do
{
Console.WriteLine("Iteration: " + i);
i++;
}
while (i < 10);
4. Foreach Loop
The foreach
loop is used to iterate over collections (like arrays, lists, etc.) without needing an index.
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{ Console.WriteLine(fruit);
}
foreach (string fruit in fruits)
{ Console.WriteLine(fruit);
}
5. Nested Loops
You can also nest loops inside each other.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine($"i: {i}, j: {j}");
}
}
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine($"i: {i}, j: {j}");
}
}
6. Break and Continue Statements
- Break: Exits the loop immediately.
- Continue: Skips the current iteration and moves to the next one.
for (int i = 0; i < 10; i++)
{
if (i == 5) break;
// Exit the loop when i is 5
Console.WriteLine(i);
}
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0) continue;
// Skip even numbers
Console.WriteLine(i);
}
{
if (i == 5) break;
// Exit the loop when i is 5
Console.WriteLine(i);
}
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0) continue;
// Skip even numbers
Console.WriteLine(i);
}
These examples cover the basics of loops in C#.