Certified ASP.NET Programmer Learning Resources Loops

Learning Resources
 

Loops


Statements execute only once as control flow passes over them. Loop constructs manipulate the flow of control to repeat certain statements over and over again. They include the for, while, do while, and foreach loops. They are extensively used in C# programs.

C# Break
The break keyword alters control flow. It has subtle yet important differences depending on its context. Break statements are used in certain parts of a program, including for-loops, foreach-loops and switch-statements.

First, this example shows the reserved break keyword in the for-loop and foreach-loop constructs. Note that you cannot use the word 'break' as a variable identifier as it is reserved. You can prefix it with a @ symbol such as @break.

When the intermediate language corresponding to the break statement is encountered in the program's assembly, control is immediately transferred to the statement following the enclosing block.

using System;

class Program
{
    static void Main()
    {
    // Array we loop through.
    int[] array = { 5, 10, 15, 20, 25 };
    Console.WriteLine("--- for-loop and break ---");

    // Loop through indexes in the array.
    for (int i = 0; i < array.Length; i++)
    {
        Console.WriteLine(array[i]);
        if (array[i] == 15) // See if the element has value of 15.
        {
        Console.WriteLine("Value found");
        break;
        }
    }
    Console.WriteLine("--- foreach-loop and break ---");
    foreach (int value in array) // Use foreach loop
    {
        Console.WriteLine(value);
        if (value == 15) // See if the iteration variable has value of 15.
        {
        Console.WriteLine("Value found");
        break;
        }
    }
    }
}

Output

--- for-loop and break ---
5
10
15
Value found
--- foreach-loop and break ---
5
10
15
Value found


The example program above uses the for-loop and foreach-loop constructs. The break keyword is often more useful in the while-loop. Internally, some of these loops are interchangeable. If you disassemble your program you will often find that there is no difference between for, while and do-while.

C# Continue
Continue alters control flow. It is used most often in loop bodies in the C# language. The continue keyword allows you to skip the execution of the rest of the iteration. It jumps immediately to the next iteration in the loop. This keyword is most useful in while loops.

Example
Note - To begin, let's look at a program that uses the continue statement in a while-true loop. In a while-true loop, the loop continues infinitely with no termination point. In this example, we use a Sleep method call to make the program easier to watch as it executes.

A random number is acquired on each iteration through the loop, using the Next method on the Random type. Then, the modulo division operator is applied to test for divisibility by 2 and 3. If the number is divisible, then the rest of the iteration is aborted, and the loop restarts.

using System;
using System.Threading;

class Program
{
    static void Main()
    {
    Random random = new Random();
    while (true)
    {
        // Get a random number.
        int value = random.Next();
        // If number is divisible by two, skip the rest of the iteration.
        if ((value % 2) == 0)
        {
        continue;
        }
        // If number is divisible by three, skip the rest of the iteration.
        if ((value % 3) == 0)
        {
        continue;
        }
        Console.WriteLine("Not divisible by 2 or 3: {0}", value);
        // Pause.
        Thread.Sleep(100);
    }
    }
}

Output

Not divisible by 2 or 3: 710081881
Not divisible by 2 or 3: 1155441983
Not divisible by 2 or 3: 1558706543
Not divisible by 2 or 3: 1531461115
Not divisible by 2 or 3: 64503937
Not divisible by 2 or 3: 498668099
Not divisible by 2 or 3: 85365569
Not divisible by 2 or 3: 184007165
Not divisible by 2 or 3: 1759735855
Not divisible by 2 or 3: 1927432795
Not divisible by 2 or 3: 648758581
Not divisible by 2 or 3: 1131091151
Not divisible by 2 or 3: 1931772589
Not divisible by 2 or 3: 283344547
Not divisible by 2 or 3: 1727688571
Not divisible by 2 or 3: 64235879
Not divisible by 2 or 3: 818135261...

Programming tip - Branch statements. The C# language is a high-level language. When it is compiled, it is flattened into a sequence of instructions. With the continue statement, branch statements are generated.

C# Goto
Statements execute one after another. With the goto statement, though, we transfer control to a named label elsewhere in the method. The C# language provides the goto statement. Goto can be used to exit a deeply nested loop. As are many things, it is considered harmful.

Example
Note - To start, we see exactly how you can use goto to exit a loop in the C# language. You can use code that does the same thing without goto, but would need a flag variable—usually a bool—to check.

using System;

class Program
{
    static void Main()
    {
    Console.WriteLine(M());
    }

    static int M()
    {
    int dummy = 0;
    for (int a = 0; a < 10; a++)
    {
        for (int y = 0; y < 10; y++) // Run until condition.
        {
        for (int x = 0; x < 10; x++) // Run until condition.
        {
            if (x == 5 &&
            y == 5)
            {
            goto Outer;
            }
        }
        dummy++;
        }
    Outer:
        continue;
    }
    return dummy;
    }
}

Output

50

Description. This code defines one custom method M. It contains three nested loops. The first loop iterates through numbers [0, 9], as do the two inner loops. However, in the third loop, a condition is checked that causes the loop to exit using the break keyword.

C# Empty Statement
An empty statement has no effect. It is the simplest and fastest statement. In an empty statement, you type a semicolon. This can be used as a loop body or elsewhere. This helps with some syntax forms such as empty while loops with no parentheses.

Example
Note - To begin, we look at the empty statement used in the body of a while loop. The empty statement does nothing, but when you use a while loop, you must always have a body for that loop, not just an iterative condition.

Sometimes, you can use a boolean method and use it as the iterative condition in the loop, and then just put in an empty statement for the loop body.

using System;

class Program
{
    static void Main()
    {
    // Use an empty statement as the body of the while loop.
    while (Method())
        ;
    }

    static int _number;

    static bool Method()
    {
    // Write the number, increment, and then return a bool.
    Console.WriteLine(_number);
    _number++;
    return _number < 5;
    }
}

Output

0
1
2
3
4

You could put an empty block { } instead of an empty statement for the loop body here; functionality would be equivalent. This is, once again, a matter of style and you should conform to whatever the rules are (if any).

 

Various loops in ASP .Net using C# are -

 For Support