C# Loops



To consider the need of loops look at the following example which prints area of a square for values of its side increasing from 1 to 5.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
	int x = 1;
	 int area;
	area = x * x;
	Console.WriteLine("Area with side = 1 is {0}",area);
    	x = 2;
    	area = x * x;
    	Console.WriteLine("Area with side = 2 is {0}", area);
    	x = 3;
    	area = x * x;
    	Console.WriteLine("Area with side = 3 is {0}", area);
    	x = 4;
    	area = x * x;
    	Console.WriteLine("Area with side = 4 is {0}", area);
    	x = 5;
    	area = x * x;
    	Console.WriteLine("Area with side = 5 is {0}", area);

        Console.ReadLine();


        }
    }
}

If you run the above program you should be able to see an output something similar to

	
Area with side = 1 is 1
Area with side = 2 is 4
Area with side = 3 is 9
Area with side = 4 is 16
Area with side = 5 is 25


While it is perfectly ok to write the above program and get the desired result. However, it has inbuilt coding and storage inefficiency. Just assume if you need to repat the same thing for 100 values of x.
It is here that the loops in C# become useful. Look at the same program using a for loop in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
	int x = 1;
        int area;
        while (x <= 5)
        {
        area = x * x;
        Console.WriteLine("Area with side = {0} is {1}", x , area);
        x = x + 1;
        }

        Console.ReadLine();


        }
    }
}

The output of the above code is exactly the same as the previous code. You will notice that this keeps the code clean and introduces some "element" of programming.
We will now formally take a look at the while loop

While Loop



syntax:
while (expression)
{
statement[s]
}

A 'while' loop executes a statement, or a block of statements wrapped in curly braces, repeatedly until the condition specified by the boolean expression returns false.

For Loop


A for loop produces results similar to while loop. However that the syntax of the for loop includes initialization.
For loops are good for when you know exactly how many times you want to perform the statements within the loop.
The contents within the for loop parenthesis holds three sections separated by semicolons (; ; ) { }.
The initializer list is a comma separated list of expressions. These expressions are evaluated only once during the lifetime of the for loop. This is a one-time operation, before loop execution. This section is commonly used to initialize an integer to be used as a counter.
Once the initializer list has been evaluated, the for loop gives control to its second section, the boolean expression. There is only one boolean expression, but it can be as complicated as you like as long as the result evaluates to true or false. The boolean expression is commonly used to verify the status of a counter variable.
When the boolean expression evaluates to true, the statements within the curly braces of the for loop are executed. After executing for loop statements, control moves to the top of loop and executes the iterator list, which is normally used to increment or decrement a counter. The iterator list can contain a comma separated list of statements, but is generally only one statement.
Probably the best way to understand a for loop is not the reading of above details but looking at the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
	 int x;
           int area;
           for (x = 1; x <= 5; x++ )
           {
            area = x * x;
            Console.WriteLine("Area with side = {0} is {1}", x, area);
                
           }

        Console.ReadLine();


        }
    }
}


When the for loop first starts the statement
x =1;
is executed. It then check the boolean expression
x<=5;
Since this is true, it enters the for loop. Inside the for loop it executes the two statements
area = x * x; Console.WriteLine("Area with side = {0} is {1}", x, area);
Next it again goes into the for loop and executes the third statement in the for loop
x++
It increases the vale of x by 1. It then again evaluates the boolean expression x<=5 and continues ....
The program comes out of the for loop when the value of x becomes 6.
There are also do while and for each loop. This will be updated later in this tutorial.

This completes your understanding of loops in C#. Loops will continue to form major building block in all the practical programs you will be doing in your real life.