YouTip LogoYouTip

Csharp Loops

# 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, and so on. Programming languages provide various control structures that allow for more complicated execution paths. Loop statements allow us to execute a statement or group of statements multiple times. The following diagram illustrates the general form of a loop statement in most programming languages: ![Image 2: Loop Structure](#) ## Loop Types C# provides several types of loops. Click the links to see the details of each type. | Loop Type | Description | | --- | --- | | (#) | Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. | | [for/foreach loop](#) | Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. | | [do...while loop](#) | Similar to the while statement, except that it tests the condition at the end of the loop body. | | (#) | You can use one or more loops inside any while, for, or do..while loop. | ## Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C# provides the following control statements. Click the links to see the details of each statement. | Control Statement | Description | | --- | --- | | (#) | Terminates the **loop** or **switch** statement and transfers execution to the statement immediately following the loop or switch. | | (#) | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. | ## Infinite Loop If the condition never becomes false, the loop becomes an infinite loop. The **for** loop can traditionally be used to create an infinite loop. Since none of the three expressions that form the for loop are required, you can make an infinite loop by leaving the conditional expression empty. ## Example ```csharp using System; namespace Loops { class Program { static void Main(string[] args) { for (; ; ) { Console.WriteLine("Hey! I am Trapped"); } } } } When the conditional expression is absent, it is assumed to be true. You may also set an initial value and increment expression, but generally, programmers prefer the for(;;) construct to represent an infinite loop.
← Csharp While LoopCsharp Nested Switch β†’