Loop Types and their Usage

As you know the code within braces is known as block of code and there will be times when you want your block of code to be repeated multiple time. In general the code executes only once and sequentially so if you want it execute multiple times then either you have to write it multiple times or use the idea of Loops.
Loops are generally a building block of any programming language. You can basically divide loops into two categories.

  1. Executes while a condition is met
  2. Executes for a specific number of times

Loops: Executes While a Conditions is Met
There will be time when you want some piece of code to be executed over and over again until a specific condition is met. For example you want to keep reading data from a file until the file comes to an end. In this scenario you have two options to use

  1. While loop
  2. Do while loop

While Loop

While loop executes until the condition given to it proves false.

Basic Syntax
     while (condition)
            {
                //code that should be repeated
            }
You use while loop construct by typing “while” keyword then giving any condition inside those parenthesis then you have your block of code that you want to execute until that condition proves false.

Coding Example
 class Program
    {
        static void Main(string[] args)
        {
            int odd = 5;
            int even = 10;
            while (odd < even)
            {
                Console.WriteLine("The odd value is {0} and even value is {1}", odd, even);
                odd += 2;
            }
            Console.ReadLine();
        }
    }
Output

In this example the loop executes three times each time it output values then update the odd value. As for condition we want loop to execute until our odd value becomes larger than even value. In fourth turn the value of odd becomes larger than even value which breaks the loop.

Do While Loop
Do while loop is a close cousin to while loop. It works same as while loop with just one exception that in do while loop the condition is checked at the end of loop. Do while loop executes at least one time whether the initial condition is false because it checks the condition at the end of one iteration (one execution of block of code is known as one iteration).

Basic Syntax
do {
                //code that should be repeated
            } while( condition);
To use do while loop you write in the “do” keyword then give your block of code that should be repeated then you write in “while” keyword and in the parenthesis  you write in the condition.

Coding Example
    class Program
    {
        static void Main(string[] args)
        {
            int odd = 15;
            int even = 10;
            do {
                Console.WriteLine("The odd value is {0} and even value is {1}.", odd, even);
		odd += 2;
            } while( odd < even);
            Console.ReadLine();
        }
    }
Output

In this example you can see that even though the odd value is already greater than even value but yet the loops executes one time before it checks the condition and give use the output. After that it terminates.

Note: It is very important to check your condition. You should provide a condition that should proves false at some point. If that condition is true at all level then your loop while becomes infinite loop and your code will never ends. So always make sure that you are providing a situation where your condition becomes false.

Executes for a Specific Number of Times
These are loops that run for a number of times that are predefined. For example that a block of code executes for 10 times or you want to run a piece of code for a specific number of elements in a data structure (we will cover that in future). There are following options for these situation

  1. Foreach Loop
  2. For Loop
Foreach Loop
If you are following along with all the tutorials I have learned and you don’t know much about collection then you might to skip foreach loop (we will discuss it in collections).
Foreach loop, loops over all the elements in your collection. The best thing about it that you don’t have to manage any counter by yourself the foreach loop will take care of it for you.

Basic Syntax
foreach (Object obj in collection)
            { 
                //code to execute
            }
You use “foreach” keyword and within parenthesis you declare a object of type of your collection then use “in” keyword and the name of your collection. Then you place the block of code you want to execute.

Coding Example

    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arr = new ArrayList();
            arr.Add("1");
            arr.Add("2");
            arr.Add("3");
            foreach (Object obj in arr)
            {
                Console.WriteLine("data is {0}", obj);
            }
            Console.ReadLine();
        }
    }
Output

Note that foreach loop is read only and you can manipulate the values of collection within foreach loop.

For Loop
“For loop” is most common loop that is used in programming. In for loop you define that how many times you want to repeat this loop?

Basic Syntax
            for (intilize; condition; increment/decrement) { 
                //code that executes repeatedly
            }
For loop is compact statement of three statements which are all optional means you can skip them. To use for loop, you use “for” keyword and within parenthesis you have three statements. Firstly the initialization of counter variable it will be executed only at the start of loop. Secondly the condition that will be checked before each iteration and if proved false the loop terminates. Lastly the statement that will be executed at the end of each loop usually it is increment or decrement.

Coding Example
    class Program
    {
        static void Main(string[] args)
        {
            int num = 2;
            for (int i = 1; i <= 10; i++ )
            {
                Console.WriteLine("{0} * {1} = {2}", num, i, num*i);
            }
            Console.ReadLine();
        }
    }
Output

In this example we use for loop to print the table for 2. In for loop we initialize the counter variable to 1. We want to print the table till 10 thus in condition we tell the compiler to run the loop until counter variable is less than 10. After each loop we want counter variable to be increased by 1 so we simple used the increment operator.

Note: All three statements in for loop are optional which means that you can skip one or more or all statements which will cause loop to be infinite. But depending on your requirement you can maneuver the loop.

Hope this article is help to you. If you have any questions or suggestion feel free to comment.

<< Operator and Expressions
Tags: C-sharp
comments powered by Disqus