Easy Tutorial
❮ Csharp Array Csharp Tutorial ❯

C# Loops

Sometimes, it may be necessary to execute the same block of code multiple times. Normally, statements are executed sequentially: the first statement in a function is executed first, followed by 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. Below is the general form of a loop statement in most programming languages:

Loop Types

C# provides the following types of loops. Click on the links to see the details of each type.

Loop Type 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 Loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do...while Loop Similar to a while statement, except that it tests the condition at the end of the loop body.
Nested Loops You can use one or more loops within any other 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 on the links to see the details of each statement.

Control Statement Description
break Statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
continue Statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Infinite Loops

If the condition never becomes false, the loop will become an infinite loop. The for loop is traditionally used for this purpose. Since none of the three expressions that form the loop are required, you can make an endless loop by leaving the conditional expression empty.

Example

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 can also set an initial value and an increment expression, but in general, programmers prefer to use the for(;;) construct to denote an infinite loop.

❮ Csharp Array Csharp Tutorial ❯