C# Loops
Sometimes, you may need to execute the same block of code multiple times. Generally, statements are executed sequentially: the first statement in a function is executed first, then the second statement, and so on.
Programming languages provide various control structures that allow more complex execution paths.
Loop statements allow us to execute a statement or group of statements multiple times; below is the general form of loop statements in most programming languages:
Loop types
C# provides the following loop types. Click the links to view details of each type.
| Loop types | Description |
|---|---|
| while loop | Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
| for/foreach loops | Executes a sequence of statements multiple times, simplifying the code for managing loop variables. |
| do...while loop | Similar to the while statement except that it tests the condition at the end of the loop body. |
| Nested Loops | You can use one or more loops inside a while, for, or do..while loop. |
Loop control statements
Loop control statements change the normal sequence of execution. When execution leaves a scope, all automatic objects created in that scope are destroyed.
C# provides the following control statements. Click the links to view details of each statement.
| Control statement | Description |
|---|---|
| break statement | terminates loop or switch statement; program flow continues to the next statement immediately following the loop or switch. |
| continue statement | Skip the current loop iteration and start the next one. |
Infinite loop
If the condition never becomes false, the loop becomes an infinite loop.for loops can be used to implement infinite loops in the traditional sense. Since none of the three expressions that make up the loop is required, you can leave some condition expressions empty to form an infinite loop.
Example
using
System
;
namespace
Loops
{
class
Program
{
static
void
Main
(
string
[
]
args
)
{
for
(
;
;
)
{
Console
.
WriteLine
(
"Hey! I am Trapped"
)
;
}
}
}
}
When the condition expression is absent, it is assumed to be true. You can also set an initial value and an increment expression, but in general, programmers prefer to use the for(;;) construct to represent an infinite loop.