Search This Blog

Friday, 20 July 2012

Loops


Loops sometimes have complicated terminating conditions. They do not progress through a simple range of numbers.

The while loop

 

It uses a controlling expression. This expression is evaluated before the loop body statements are executed. It is important to avoid infinite loops.


Example:

class Program
    {
        static void Main(string[] args)
        {
            int number = 0;
 
            while(number < 5)
            {
                Console.WriteLine(number);
                number = number + 1;
            }
 
            Console.ReadLine();
        }
    }

The do loop

 

The opposite is true for the do loop, which works like the while loop in other aspects through. The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once. 

do
{
    Console.WriteLine(number);
    number = number + 1;
} while(number < 5);

The for loop

 

The for loop is a bit different. It's preferred when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount. Here is an example on the for loop. 

class Program
    {
        static void Main(string[] args)
        {
            int number = 5;
 
            for(int i = 0; i < number; i++)
                Console.WriteLine(i);
 
            Console.ReadLine();
        }
    }

The foreach loop

 

The last loop we will look at, is the foreach loop. It operates on collections of items, for instance arrays or other built-in list types. In our example we will use one of the simple lists, called an ArrayList. It works much like an array, but don't worry, we will look into it in a later chapter. 

using System;
using System.Collections;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {            
            ArrayList list = new ArrayList();
            list.Add("John Doe");
            list.Add("Jane Doe");
            list.Add("Someone Else");
            
            foreach(string name in list)
                Console.WriteLine(name);
 
            Console.ReadLine();
        }
    }
}
 


Next Chapter
 

No comments:

Post a Comment