Wednesday, August 4, 2010

Lesson 4: Control Statements - Loops

In the last lesson, you learned how to create a simple loop by using the goto statement. I advised you that this is not the best way to perform loops in C#. The information in this lesson will teach you the proper way to execute iterative logic with the various C# looping statements. Its goal is to meet the following objectives:

    * Learn the while loop.
    * Learn the do loop.
    * Learn the for loop.
    * Learn the foreach loop.
    * Complete your knowledge of the break statement.
    * Teach you how to use the continue statement.

The while Loop

A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Its syntax is as follows: while () { }. The statements can be any valid C# statements. The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the while loop to check the boolean expression again.

When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state. During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to. Listing 4-1 shows how to implement a while loop.
Listing 4-1. The While Loop: WhileLoop.cs

    using System;

    class WhileLoop
    {
        public static void Main()
        {
            int myInt = 0;

            while (myInt < 10)
            {
                Console.Write("{0} ", myInt);
                myInt++;
            }
            Console.WriteLine();
        }
    }

Listing 4-1 shows a simple while loop. It begins with the keyword while, followed by a boolean expression. All control statements use boolean expressions as their condition for entering/continuing the loop. This means that the expression must evaluate to either a true or false value. In this case we are checking the myInt variable to see if it is less than (<) 10. Since myInt was initialized to 0, the boolean expression will return true the first time it is evaluated. When the boolean expression evaluates to true, the block immediately following the boolean expression will be executed.

Within the while block we print the number and a space to the console. Then we increment (++) myInt to the next integer. Once the statements in the while block have executed, the boolean expression is evaluated again. This sequence will continue until the boolean expression evaluates to false. Once the boolean expression is evaluated as false, program control will jump to the first statement following the while block. In this case, we will write the numbers 0 through 9 to the console, exit the while block, and print a new line to the console.
The do Loop

A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time. On the other hand, a while loop evaluates its boolean expression at the beginning and there is generally no guarantee that the statements inside the loop will be executed, unless you program the code to explicitly do so. One reason you may want to use a do loop instead of a while loop is to present a message or menu such as the one in Listing 4-2 and then retrieve input from a user.
Listing 4-2. The Do Loop: DoLoop.cs

    using System;

    class DoLoop
    {
        public static void Main()
        {
            string myChoice;

            do
           {
                // Print A Menu
                Console.WriteLine("My Address Book\n");

                Console.WriteLine("A - Add New Address");
                Console.WriteLine("D - Delete Address");
                Console.WriteLine("M - Modify Address");
                Console.WriteLine("V - View Addresses");
                Console.WriteLine("Q - Quit\n");

                Console.WriteLine("Choice (A,D,M,V,or Q): ");

                // Retrieve the user's choice
                myChoice = Console.ReadLine();

                // Make a decision based on the user's choice
                switch(myChoice)
                {
                    case "A":
                    case "a":
                        Console.WriteLine("You wish to add an address.");
                        break;
                    case "D":
                    case "d":
                        Console.WriteLine("You wish to delete an address.");
                        break;
                    case "M":
                    case "m":
                        Console.WriteLine("You wish to modify an address.");
                        break;
                    case "V":
                    case "v":
                        Console.WriteLine("You wish to view the address list.");
                        break;
                    case "Q":
                    case "q":
                        Console.WriteLine("Bye.");
                        break;
                    default:
                        Console.WriteLine("{0} is not a valid choice", myChoice);
                        break;
                }

                // Pause to allow the user to see the results
                Console.Write("press Enter key to continue...");
                Console.ReadLine();
                Console.WriteLine();
            } while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit
        }
    }

Listing 4-2 shows a do loop in action. The syntax of the do loop is do { } while ();. The statements can be any valid C# programming statements you like. The boolean expression is the same as all others we've encountered so far. It returns either true or false.

In the Main method, we declare the variable myChoice of type string. Then we print a series of statement to the console. This is a menu of choices for the user. We must get input from the user, which is in the form of a Console.ReadLine method which returns the user's value into the myChoice variable. We must take the user's input and process it. A very efficient way to do this is with a switch statement. Notice that we've placed matching upper and lower case letters together to obtain the same functionality. This is the only legal way to have automatic fall through between cases. If you were to place any statements between two cases, you would not be able to fall through. Another point is that we used the default: case, which is a very good habit for the reasons stated in Lesson 3: Control Statements - Selection.
The for Loop

A for loop works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold 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. Listing 4-3 shows how to implement a for loop. The purpose of the program is to  print only odd numbers less than 10.
Listing 4-3. The For Loop: ForLoop.cs

    using System;

    class ForLoop
    {
        public static void Main()
        {
            for (int i=0; i < 20; i++)
            {
                if (i == 10)
                    break;

                if (i % 2 == 0)
                    continue;

                Console.Write("{0} ", i);
            }
            Console.WriteLine();
        }
    }

Normally, for loop statements execute from the opening curly brace to the closing curly brace without interruption. However, in Listing 4-3, we've made a couple exceptions. There are a couple if statements disrupting the flow of control within the for block.

The first if statement checks to see if i is equal to 10. Now you see another use of the break statement. Its behavior is similar to the selection statements, as discussed in Lesson 3: Control Statements - Selection. It simply breaks out of the loop at that point and transfers control to the first statement following the end of the for block.

The second if statement uses the remainder operator to see if i is a multiple of 2. This will evaluate to true when i is divided by 2 with a remainder equal to zero, (0). When true, the continue statement is executed, causing control to skip over the remaining statements in the loop and transfer back to the iterator list. By arranging the statements within a block properly, you can conditionally execute them based upon whatever condition you need.

When program control reaches either a continue statement or end of block, it transfers to the third section within the for loop parentheses, the iterator list. This is a comma separated list of actions that are executed after the statements in the for block have been executed. Listing 4-3 is a typical action, incrementing the counter. Once this is complete, control transfers to the boolean expression for evaluation.

Similar to the while loop, a for loop will continue as long as the boolean expression is true. When the boolean expression becomes false, control is transferred to the first statement following the for block.

For this tutorial, I chose to implement break and continue statements in Listing 4-3 only. However, they may be used in any of the loop statements.
The foreach Loop

A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace. The syntax of a foreach loop is foreach ( in ) { }. The type is the type of item contained in the list. For example, if the type of the list was int[] then the type would be int.

The iteration variable is an identifier that you choose, which could be anything but should be meaningful. For example, if the list contained an array of people's ages, then a meaningful name for item name would be age.

The in keyword is required.

As mentioned earlier, the list could be either an array or a collection. You learned about arrays in Lesson 02: Operators, Types, and Variables. You can also iterate over C# generic collections also, described in Lesson 20: Introduction to Generic Collections.

While iterating through the items of a list with a foreach loop, the list is read-only. This means that you can't modify the iteration variable within a foreach loop. There is a subtlety here; Later, you'll learn how to create custom types, called class and struct, that can contain multiple fields.  You can change the fields of the class or struct, but not the iteration variable for the class or struct itself in a foreach loop.

On each iteration through a foreach loop the list is queried for a new value. As long as the list can return a value, this value will be put into the read-only iteration variable, causing the statements in the foreach block to be executed. When the collection has been fully traversed, control will transfer to the first executable statement following the end of the foreach block. Listing 4-4 demonstrates how to use a foreach loop.
Listing 4-4. The ForEach Loop: ForEachLoop.cs

    using System;

    class ForEachLoop
    {
        public static void Main()
        {
            string[] names = {"Cheryl", "Joe", "Matt", "Robert"};

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

In Listing 4-4, the first thing we've done inside the Main method is declare and initialize the names array with 4 strings. This is the list used in the foreachloop.

In the foreach loop, we've used a string variable, person, as the item name, to hold each element of the names array. As long as there are names in the array that have not been returned, the Console.WriteLine method will print each value of the person variable to the screen.
Summary

Loops allow you to execute a block of statements repeatedly. C# offers several statements to construct loops with, including the while, do, for, and foreach loops. while loops execute a block of statements as long as an expression is true, do loops execute a block of statements at least once and then keep going as long as a condition is true, for loops execute a block of statements a specified amount of times, and foreach loops execute a block of statements for each item in a collection. Normally a block of statements will execute from beginning to end. However, the normal flow of a loop can be changed with the break and continue statements.

So far, the only method you've seen in this tutorial is the Main method, which is the entry point of a C# application. However, you are probably wanting to write larger programs to test your new knowledge. This requires breaking up the code into methods to keep it organized and logical. For this, I invite you to return for Lesson 5:  Introduction to Methods, where you can learn new techniques of organizing your code.

Your feedback and constructive contributions are welcome.  Please feel free to contact me for feedback or comments you may have about this lesson.

No comments:

Post a Comment