Lesson 4: Loops

Loops are for running sections of code multiple times. Loops in C# are extremely similar to Java, and most programming languages in general. Double check your brackets! This is very useful for creating or changing a lot of things at once. There are four main ways to loop. Remember the loop is considered 1 statement, so no need to end with a semicolon(EXCEPT FOR DO WHILE!) and make sure the brackets enclose all the code inside.

  1. While loop
  2. for loop
  3. do while loop
  4. foreach

The while loop is the most basic loop. If a boolean condition is met, it will loop through the code. They key thing is that the condition is tested before the loop starts. Here is an example:

 class Program
    {
        static void Main() 
        {
            int n = 1;
            while (n < 6) 
            {
                Console.WriteLine("Current value of n is {0}", n);
                n++;
            }
        }
    }

The next loop is the For loop.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

The for loop is in the following format:

for ( init; condition; increment )
{
   statement(s);
}

Here is an example that will count from 0 – 10. As you can see, it starts from variable a, that is at 0, and it will loop until it is 10, and each loop it adds up by 1.

namespace loops
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int a = 0; a <= 10; a= a + 1)
            {
                Console.WriteLine("value of a: {0}", a);
            }
            Console.ReadKey();
        }
    }
}

Lastly there is do while loops. Do while are loops are identical to while loops, except that the code is ran once before the loop condition is checked. Remember it runs once no matter what.
Do while is in the following style:

do
{
   statement(s);

}while( condition );

And here is an example. Notice how it outputs “Rito Plz” no matter what. Try and change the variables to true and false to see how the do while works. Do while do end in a semicolon.

namespace loops
{
    class Program
    {
        static void Main(string[] args)
        {
            Boolean serversUp = false;
            do
            {
                Console.WriteLine("Rito Plz");
            } while (serversUp);

        }
    }
}

and here is a more advanced example:

namespace Loops
{
    
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            do
            {
               Console.WriteLine("value of a: {0}", a);
                a = a + 1;
            } while (a < 20);

            Console.ReadLine();
        }
    }
} 

Lastly there is the foreach loop. It is similar to Java’s enhanced for in loop. This loop is useful for looping through arrays/collections. In java it is:

for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }

in C# it is:

foreach (string name in names)
{
Console.WriteLine(name);
Console.WriteLine(",");
}

Here is a full example:

    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
        foreach (int element in fibarray)
        {
            Console.WriteLine(element);
        }
        Console.WriteLine();


        // This is the above loop in a traditional for loop. Notice how it is simpler.
        for (int i = 0; i < fibarray.Length; i++)
        {
            Console.WriteLine(fibarray[i]);
        }
        Console.WriteLine();


        // You can maintain a count of the elements in the collection/array. 
        int count = 0;
        foreach (int element in fibarray)
        {
            count += 1;
            Console.WriteLine("Element #{0}: {1}", count, element);
        }
        Console.WriteLine("Number of elements in the array: {0}", count);
        Console.ReadKey();
    }
    // Output: 
    // 0 
    // 1 
    // 1 
    // 2 
    // 3 
    // 5 
    // 8 
    // 13 

    // 0 
    // 1 
    // 1 
    // 2 
    // 3 
    // 5 
    // 8 
    // 13 

    // Element #1: 0 
    // Element #2: 1 
    // Element #3: 1 
    // Element #4: 2 
    // Element #5: 3 
    // Element #6: 5 
    // Element #7: 8 
    // Element #8: 13 
    // Number of elements in the array: 8
}

In loops there are key words or statements. They include break, continue, and goto. Break immediately ends the loop and exits out of it. Continue instantly jumps to the next iteration of the loop. In most cases this is the beginning of the loop. Goto goes to a label or a case. For example

goto cool;

will go to somewhere labeled:

cool:

See more here:
http://www.tutorialspoint.com/csharp/csharp_loops.htm
http://msdn.microsoft.com/en-us/library/f0e10e56%28v=vs.90%29.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *