C# For Iterations

For Iterations are used to loop a block of code over and over again.

Syntax

   for (int i = 0; i < length; i++)
  {  

  }

Tip: In the VS studio IDE, if you type for until it’s highlighted and then hit tab twice, the syntax will automatically be inserted.

Create a new C# console project and name it ForIterations.

Example

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

Hit F5 and you should see the numbers 0 – 9 print out.

How does it work?

First in our For Iteration statement we have some variables in the brackets. Let’s break that apart:

(int i = 0; i < 10; i++)

You first have a new variable named i with the data type int and value 0 (int i = 0;). Then you have i < 10, which basically means ‘if i is less than 10’, which it is, so the next line says increment i until it reaches 9. Then you have the Console.WriteLine which prints out the results and Console.ReadLine( ) which reads out the line.

Starting the iteration from a specific number

The above example is a simple For Iteration statement, however as you can see the numbering starts from 0, so it prints 0 – 9 and not 10. We can force it to start from a specific number, in this case we use 1 + x (x = the integer to start from).

 for (int i = 0; i < 10; i++)
    {
      Console.WriteLine (i+1);              
    }
    Console.ReadLine();

When you run it this time you should see the numbers 1 – 10. However, if you want it to go from 0 – 10 you can use the less than or equal to operator.

for (int i = 0; i <= 10; i++)
    {
      Console.WriteLine (i);              
    }
    Console.ReadLine();

Incrementing from a specific value

In the above two examples the numbers always incremented by 1 as that is default, however you can choose to start from 2, 3 or any other number.

 for (int i = 0; i < 20; i+=2)
    {
     Console.WriteLine(i + 2);
    }
    Console.ReadLine();

When you run that code you should see the numbers 2, 4, 6, 8, all the way to 20. We incremented by 2 and also started from 2.

Foreach Loop

Another type of iteration is foreach, which can loop through a collection of elements such as an array.

Syntax

 foreach (var item in collection)
            {                

            }

Example

   string[] car = new string[]{"Audi", "BMW", "Mazda", "Lexus", "Toyota", "Range Rover"};

            foreach (var item in car)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();

In this example we first created an array of strings, and then used the foreach statement to loop through and print each value. The variable which is created (item) is local to this foreach statement and cannot be used outside of it.

Real Life Example

In this example we will create a list of folders from the program files folder.

Before starting you need the SystemIO namespace above; this allows us to read/write data streams.

using System.IO;
      var folders  = Directory.GetDirectories(@"C:\Program Files\");

            foreach (var folder in folders)
            {
                Console.WriteLine(folder);
            }

            Console.ReadLine();

This will get all the folders in the program files directory.

Summary

  • To start increment from a different number you do i+=x (x is the integer you want to increment from)
  • To start from a specific number you do i + x (x is the integer you want to start from)
  • The variables are local to the foreach and For Iterations