Control Statements

 

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 (<boolean expression>) { <statements> }. 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 { <statements> } while (<boolean expression>);. 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 good for when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parenthesis holds three sections separated by semicolons (<initializer list>; <boolean expression>; <iterator list>) { <statements> }.

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.

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 (<type> <item name> in <list>) { <statements> }. 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 item name 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, as defined by types found in the System.Collections namespace. You learned about arrays in Lesson 02: Operators, Types, and Variables. If you aren't familiar with collections, open the .NET Framework SDK documentation and look for the System.Collections namespace to see what types are available.

While iterating through the items of a list with a foreach loop, the list is read-only. This means that you can't change the value of any items in the list within 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 item name 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.

 


Selection statements

If and switch are considered selection statements because they assist in determining the logical path code would take depending on certain conditions. Here's more information about both statements.

The if statement
This statement works with an expression that evaluates to a Boolean value. If the Boolean expression evaluates to true, the statement embedded in the if clause will be executed. If the Boolean expression evaluates to false, the statement in the if clause will not be executed.

The if statement can be followed by an else statement that is executed if the Boolean expression used in the if clause evaluates to false. An else statement can also be used in combination with if. In that instance, it works in a similar way to the ordinary if statement; however, this section of the code is only analyzed if the Boolean expression in the first if clause evaluates to false and the expression in this else if clause evaluates to true.

In general, it's a good practice to utilize the else keyword in order to make sure that all possible scenarios are being handled in the code and can't fall through the cracks in program logic.

Note: When utilizing the if statement to check for equality, you have to use two consecutive equals signs. Two equals signs check for equality, whereas one equals sign simply performs an assignment.

The following is an example of an if statement:

            int i=3;
            if (i == 1)
            {MessageBox.Show("i=1"); }
            elseif (i==2)
            {MessageBox.Show("i=2"); }
            else
            { MessageBox.Show("i=?"); }

The switch statement
This statement evaluates an expression and compares the expression's value to a number of cases. Each case is associated with a statement list that is called a switch section. C# executes a statement list associated with the switch section that matches the expression's value. Switch is an easy-to-read programming alternative to having many if/else pairs whenever you are trying to evaluate a value of a particular expression.

The expression used as the driver for the switch statement is displayed in parentheses that follow the switch keyword. In general, the expression used in the switch statement must evaluate to one of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. You can also utilize an expression that can be implicitly converted to one of the above types.

Switch sections start with the keyword case, which is followed by a constant expression. A colon follows the constant expression, and the statement list follows the colon. The break specifies the end of the statement block.

First, C# evaluates the expression in the switch statement. It then looks for a switch block whose expression matches the expression's value. If it can find the matching value in one of the switch sections, the statement list for the switch section executes.

The default keyword in the switch blocks is utilized to execute a particular section of the code whenever none of the cases listed match the value switch block's constant value.

In general, it's a good practice to utilize the default keyword in order to make sure that all possible scenarios are being handled in the code and can't fall through the cracks in program logic.

The following is an example of a switch statement:

            int i=3;
            switch (i)
            {
                case 1:
                    MessageBox.Show("i=1");
                    break;
                case 2:
                    MessageBox.Show("i=2");
                    break;
                default:
                    MessageBox.Show("i=?");
                    break;
            }

Iteration statements

While, do, for, and foreach are considered iteration statements because they assist in executing embedded statements multiple times. Here's more information about the four statements.

The while statement
This statement executes a statement list while an expression evaluates to True. The Boolean expression that controls the while statement is enclosed in parentheses that follow the while keyword. The statements that should be executed while the Boolean expression evaluates to True follow the parentheses.


 

The following is an example of a while statement:

            int i=3;
           
            while (i < 5 )
            {
            MessageBox.Show(i.ToString());
            i++;
            }

The do statement
This statement executes its embedded statements zero or more times. If the Boolean expression used in the while statement evaluates to false, then none of the embedded statements will be executed. However, in order to ensure that the embedded statements are executed at least once, you can use a do statement.

The do statement is followed by embedded statements, which are followed by a while keyword. The Boolean expression that controls the number of times that the loop executes follows the while keyword. The embedded statements will be executed at least once since the Boolean expression is evaluated after the embedded statements execute.

This is an example of a do statement:

      int i=3;


            do
            {
                MessageBox.Show(i.ToString());
                i++;
            }
            while (i < 3);

The for statement
This statement begins with the for keyword and is followed by parentheses. The parentheses contain an initializer, a condition, and an iterator statement, all separated by semicolons. The embedded statements follow the parentheses.

This is an example of a for statement:

           for (int i=0; i<4; i++)
            {
                MessageBox.Show(i.ToString());
            }
         }

 

The foreach statement
This statement is used to iterate over the elements in a collection. Since arrays in C# provide support for the foreach statement, you can use the foreach statement to work with each element in the array.

To use the foreach statement, type the foreach keyword, followed by parentheses. The parentheses must contain the following information: the type of the element in the collection; the identifier name for an element in the collection; the keyword in; and the identifier of the collection. Embedded statements follow the parentheses.

This is an example of a foreach statement:

    int[] intArray;
            intArray = newint[3];


            intArray[0] = 0;
            intArray[1] = 1;
            intArray[2] = 2;


            foreach (int ArrayElement in intArray)
                MessageBox.Show(ArrayElement.ToString());

Jump statements

Break, continue, and goto are considered jump statements because they assist in jumping to a specific statement within code. Here's more information about the three statements.

The break statement
This statement is often used in conjunction with switch statements; however, C# allows you to use it to break out of the current block of statements. The break statement is usually used to break out from an iteration statement block.

This is an example of a break statement:

int i = 0;


            while (i < 4)
            {
                MessageBox.Show(i.ToString());
                if (i == 2)
                    break;
                i++;
            }

The continue statement
This statement returns the control back to the Boolean expression that controls an iteration statement.

This is an example of a continue statement:

for (inti = 1; i <= 4; i++) 


        {
            if (i < 2)
            {
                continue;
            }
            MessageBox.Show (i);
        }

The goto statement
This statement transfers control to a labeled statement unconditionally. In C#, any statement can be labeled. A colon follows a statement label, and a label identifier follows the goto keyword. The goto statement transfers control to the statement named by the label identifier.

If you overuse the goto statement, it can create code that is hard to read and follow. In general, it's a good practice to avoid using goto altogether by restructuring the code in a way that allows you to get around using the goto statements.

This is an example of a goto statement:

    int i = 0;
            while (i < 3)
            {
                MessageBox.Show(i.ToString());
                if (i == 2)
                    goto Complete;
                i++;
            }
        Complete: MessageBox.Show("complete");