Loops
Understanding Loops in C#
Loops are powerful programming constructs that allow you to execute a block of code multiple times. This capability is useful in many situations, for example, when you have to process each item in a collection or repeat an operation a certain number of times. In this article, we'll explore the various types of loops available in C#.
The for
Loop
The for
loop is a control flow statement that allows code to be executed repeatedly. The structure of a for
loop is as follows:
for (initialization; condition; increment)
{
// code to be executed
}
- The
initialization
is executed once at the beginning of the loop. - The
condition
is evaluated before each loop iteration. If the condition is true, the loop statements execute. If it is false, the loop terminates. - The
increment
statement is invoked after each iteration.
Here's an example of a for
loop:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
This loop will output the numbers 0 through 4.
The while
Loop
The while
loop repeatedly executes a block of statements as long as a specified condition is true. The structure of a while
loop is:
while (condition)
{
// code to be executed
}
For example:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
This loop will output the same as the for
loop above.
The do-while
Loop
The do-while
loop is similar to the while
loop with one key difference: it checks the condition after the loop has executed, guaranteeing at least one run of the loop, even if the condition is false. The structure of a do-while
loop is:
do
{
// code to be executed
}
while (condition);
For example:
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 5);
Again, this loop will output the same as the previous examples.
The foreach
Loop
The foreach
loop is used to iterate over collections (like arrays or lists). The structure of a foreach
loop is:
foreach (type variable in collection)
{
// code to be executed
}
For example:
string[] names = { "John", "Jane", "Jim", "Jill" };
foreach (string name in names)
{
Console.WriteLine(name);
}
This loop will output all the names in the names
array.
Loop Control Statements
C# includes two keywords - break
and continue
- that can be used to change the normal flow of loop execution.
break
: Terminates the loop and transfers execution to the statement immediately following the loop.continue
: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
This loop will output the numbers 0 through 4. When i
becomes 5, the break
statement ends the loop.
Loops are a fundamental part of programming in C#. They allow for repetitive tasks to be done efficiently and effectively. By understanding the different types of loops and how to use them, you can write better, more efficient code. Happy coding!