Implementing the for loop iteration logic



Iteration provides a convenient way to execute a block of code multiple times. Visual C# provides a number of standard constructs known as loops that you can use to implement iteration logic.

Using the for loop

The for loop executes a block of code repeatedly until the specified expression evaluates to false.

You can define a for loop as follow:

    
    namespace UsingFor
    {
        class Program
        {
            static void Main(string[] args)
            {
               for ([initializers]; [expression]; [iterators])
                {
                [body]
                }
            }
        }
    }

When using a for loop, you first initialize a value as a counter. On each loop, you check that the value of the counter is within the range to execute the for loop, and if so, execute the body of the loop.

The following code example shows how to use a for loop:

    
    using System;
    using System.Text;
    namespace ForIterations
    {
        class Program
        {
            static void Main(string[] args)
            {
                int power;
                Console.WriteLine("Quadratic of first 10 numbers:");
                for (int myValue = 0; myValue < 11; myValue++)
                {
                    power = myValue * myValue;                    
                    Console.Write(power+" ");
                }
                Console.ReadLine();
            }
        }
    }

    Output:
    Quadratic of first 10 numbers:
    0 1 4 9 16 25 36 49 64 81 100

Using the foreach loops

While a for loop is easy to use, it can be tricky to get right. For example, when iterating over a collection or an array, you have to know how many elements the collection or array contains.

In many cases this is straightforward, but sometimes it can be easy to get wrong. Therefore, it is sometimes better to use a foreach loop.

The following code example shows how to use a foreach loop:

    
    using System;
    using System.Text;
    namespace ForEach
    {
       class Program
        {
            static void Main()
            {
	        string[] colors = { "RED", "BLUE", "GREEN" };
	        // ... Loop with the foreach keyword
	        foreach (string value in colors)
	        {
                Console.WriteLine("RGB colors are:");
	        Console.Write(value " ");
	    }
    }

    Output:
    RGB colors are:
    RED BLUE GREEN

Ads Right