Branching and Looping in C#, Part 2

In the first part of this article we discussed if, switch and for statements. In part 2 we will continue our looping statements (while, do/while and foreach) and we will discuss jump statements (break, continue, goto and return).

foreach statement

Visual Basic programmers have been accustomed to using the For Each loop for several years to iterate through an array or a collection. C# features a new loop construction that is easy to use and similar to VB’s For Each loop; it’s the foreach loop. As you know, you can use a for statement to loop over an array or collection, but there are some problems that you may encounter that produce logic errors.

For example, you may need to iterate through all the elements in an array using the for statement. If you declared the variable of the loop to 1, the first element in the array will not be accessed. Another problem that can occur is that you may forget and step 2 instead of one, or even worse (as in our last example in Part 1), you use a decrement step — the list of potential problems is pretty long, in fact.

The C# foreach loop is used to iterate through each and every element in an array or collection, and you don’t have to worry about anything. Although it’s little slower than the for loop, the C# compiler optimizes foreach if used with arrays. Here is the syntax of the foreach statement:

foreach(type declaration in collection)
{
  statement 1;
  statement 2;
  statement 3;
}

Let’s take an example:

using System; 
namespace MyCompany
{
  public class Loops
  { 
    static void Main(string[] args)
  {
  int[] myArray = {10, 20, 30, 40}; 
 
  foreach(int temp in myArray)
    {
      Console.WriteLine(temp);
    }
    Console.ReadLine(); 
  } 
 }
}

 
Compile and run the above code and you will get the following result.

Note that we have declared a variable of type int inside the foreach loop to hold the current array’s element, and this variable is accessible in the statement block. The foreach loop is intelligent, so for each iteration, it updates its local variable with the new element. With foreach you will not manually increase a counter and set a loop, because it will do it for you. The foreach loop comes with a cost also: you can’t assign a new value to the array’s elements, because they are read-only inside the foreach loop (via the local variable that we use). Modify the last example so it will look like this:

foreach(int temp in myArray)
{
  Console.WriteLine(temp);
  temp = 100;
}

When you compile the application you will get the following error:

“Cannot assign to ‘temp’ because it is read-only.”

If the element is not a primitive type, you can call a method of the object to modify it or update its state. You can use the foreach statement with the built-in collection classes, or with your handmade collection classes, but in this case you need to implement some interfaces that give foreach the methods to use in iteration through the objects. Anyway, this is beyond the scope of this article, so I will defer that until we discuss Data Structure and Collections with C#.

{mospagebreak title=The while Loop}

With the for loop we know in advance how many iterations we need, and with the foreach loop we know that it will loop on every and each element (or object) inside the array or inside the collection. Sometimes we need similar behavior; we need to loop through a series of statements until something happens — maybe the user wants to exit the program, or the user entered invalid data. The while loop construction looks like the following:

while(boolean expression)
{
  statement 1;
  statement 2;
  statement 3;
}

The while statement executes the block statement as long as its Boolean expression evaluates to true. You can exit the body of the while loop using a jump statement, as we will see soon. Let’s take an example. In Part 1 we wrote a simple program that tells if the entered number is even or odd, but this program can only execute one iteration, so let’s extend it.

using System;
namespace MyCompany
{
  public class Loops
  {
    static void Main(string[] args)
    {
      int x = 0; 
      while(x != -1)
      { 
        Console.WriteLine(“Please type a number, -1 to exist”); 
        x = Convert.ToInt32(Console.ReadLine());
        if(x != -1)
          {
            if(x % 2 == 0) 
            {
              if(x < 1000) 
              {
                Console.WriteLine(“this is an EVEN number”);
              }
              else
              { 
                Console.WriteLine(“this is a big EVEN number”);
              } 
            } 
            else 
            { 
              if(x < 1000)
            { 
              Console.WriteLine(“this is an ODD number”); 
            }
            else
            { 
              Console.WriteLine(“this is a big ODD number”); 
            } 
          } 
        } 
      } 
    } 
  } 
}

 
Compile and run the program.

As you can see, the program will not exit until you type -1; also note that the Boolean expression test on the value of x != -1, and in the first statement (before the while loop) we declared and assigned 0 to the variable x. So maybe the while statement never gets executed, because we may put this code in a program that will assign the value of -1 to x before the while statement. We have another way to ensure that the block will be executed at least once before testing the Boolean expression; it’s the do/while loop.

{mospagebreak title=The do/while Loop}

The previous while loop tests the Boolean expression; if it’s true, then the statement block gets executed, so we can say “while the x != 0 execute the block”. With the do/while loop, it executes the block first, then it tests the Boolean expression and loop to see whether it’s true, so we can say “do the block and loop while x != 0″. With the while loop we can’t guarantee that the statement block will be executed even once, but with the do/while loop we guarantee that the statement block will execute at least one time before it tests the Boolean expression and decides if it will loop again or not. The syntax of do/while is as follows:

do
{
  statement 1;
  statement 2;
  statement 3;
}while(Boolean expression)

Let’s modify our even/odd number example to use do/while instead of the while loop.

using System;
namespace MyCompany
{
  public class Loops
  {
    static void Main(string[] args)
    {
      int x = 0;
      do
      {
        Console.WriteLine(“Please type a number, -1 to exist”); 
        x = Convert.ToInt32(Console.ReadLine());
        if(x % 2 == 0)
        {
          if(x < 1000) 
          {
            Console.WriteLine(“this is an EVEN number”);
          }
          else 
          {
            Console.WriteLine(“this is a big EVEN number”); 
          } 
        }
        else 
        {
          if(x < 1000)
          {
            Console.WriteLine(“this is an ODD number”);
          }
          else
          { 
            Console.WriteLine(“this is a big ODD number”); 
          } 
        } 
      }while(x != -1); 
    } 
  }
}


Compile and run the application. I have made some modifications to the code, so you can see the effect of the do/while statement. When you run the example with VS.NET, run it without Debugging Mode by pressing CTRL + F5 then enter -1 as the number, and you will get the following result:

Although you entered -1, the program will execute the statements inside the block, and then test the Boolean Expression, which will evaluate to false and cause no more looping. In this “Without Debugging” mode you need to press any key to continue, which will terminate the application, because there are no more statements to execute. Some programmers say that most of the time you will be using the while loop (because you can control the execution using the Boolean Expression), and some other programmers say that do/while is a more common block than the while loop, but I tell you it’s all about your application logic — sometimes you need to execute the code one time at least, and other times you need to execute the block, depending on the value of the Boolean Expression.

We have discussed loops, but we didn’t discuss how to unconditionally exit a loop with the available jump statements, so let’s take a look.

{mospagebreak title=The goto Statement}

The go to statement, or as C# presents it now, the ‘goto’ statement, has been in programming languages for a very long time. Many programmers avoid using the goto statement because they think it produces ugly code or code that can turn the application upside down.  Actually, the problem is not the goto statement itself, it’s using the statement incorrectly. If you know exactly how to use the goto statement, it will save you a great deal of time. I will use the EVEN/ODD Numbers program to present the goto statement, but first, look at the following code.

static void Main(string[] args)
{
  int x = 0;
  Console.WriteLine(“Please enter a number, -1 to exist”);
  x = Convert.ToInt32(Console.ReadLine());
  while( x != -1) 
  { 
    if(x % 2 == 0) 
    { 
      Console.WriteLine(“This is an EVEN number”); 
    } 
    else 
    { 
      Console.WriteLine(“This is an ODD number”); 
    } 
    
Console.WriteLine(“Please enter a number, -1 to exist”);
    x = Convert.ToInt32(Console.ReadLine()); 
  } 
}

This is fine, and it will compile and run, but this code has some problems. The first problem is that there are duplicate statements, because the program needs the value of the number before the while loop so it can test its Boolean expression, and it needs it again at the end of the iteration to set the new value of x. Actually, well designed code for this kind of problem states “I read a value then if it passes the Boolean Expression I process the value and if not I stop.” This is not the case in our little program, because we read the value once before the loop, and again inside the loop, so we need to rewrite the above code:

using System;
namespace MyCompany
{
  public class Loops
  {
    static void Main(string[] args)
    {
      int x = 0; 
      while(true) 
      { 
        Console.WriteLine(“Please enter a number, -1 to exist”); 
        x = Convert.ToInt32(Console.ReadLine()); 
        if(x == -1) 
        { 
          goto exist; 
        } 
    

        if(x % 2 == 0) 
        { 
          Console.WriteLine(“This is an EVEN number”); 
        } 
        else 
        { 
          Console.WriteLine(“This is an ODD number”); 
        } 
      } 

      exist: 
      { 
        Console.WriteLine(“Program exist, press the enter key”); 
        Console.ReadLine(); 
      } 
    } 
  } 
}

 
Compile and run the application and you will get the following result:

As you can see, we get the same result, but the code is a little different from before. Note that we have used the true keyword with the while statement, so it will evaluate to true, and it results in an infinite loop; the value will be tested, and if it’s -1, we jump to the label exist using the goto keyword, which terminates the application. You may say that you can use the break statement instead of goto, and we will get the same results, and yes, you are correct in this example — but there are times where you have more than one label, and you need to jump to them depending upon the value you have. Another famous use of the goto statement is with the switch case statement, so let’s take an example.

static void Main(string[] args)
{
  int x = Convert.ToInt32(Console.ReadLine());
  bool result = (x % 2 == 0);
  switch(result)
  {
    case true:
      Console.WriteLine(“EVEN NUMBER”);
      goto default;
    case false:
      Console.WriteLine(“ODD NUMBER”);
      goto default;
    default:
      Console.WriteLine(“hit the Enter key to exist”);
      Console.ReadLine();
      break;
  }
}

This is another variation of the EVEN/ODD Number story, but this time we used a switch statement to check if it’s an even or odd number, and in either case we goto the default section, where we write the line “hit the Enter key to exist” and wait until the user does just that. Note that there are no break statements in the first two case statements because they don’t actually need them; either case will end up in the default section, which actually needs the break statement to exist. When you know how to use the goto statement, it will save you a great deal of time when your algorithm is complex.

{mospagebreak title=The return statement}

The return statement is used commonly with methods in two scenarios. You can use the return statement with a void method to exit to the caller; note that code which comes after the return method will not be executed, as in the following example

public class Loops
{
  static void Main(string[] args)
  {
    TestMethod();
    Console.ReadLine();
  }

  static void TestMethod()
  {
    Console.WriteLine(“Here we will return”);
    return;
    Console.WriteLine(“Do you see this line?”);
  }
}

The result of this application is:

The method call after the return statement will not execute, because return will terminate the method call and return to the caller. The common use of return is to return a value to the caller other than void, so it will be used with methods that has a return type. It’s not clear that the return statement call must be the last statement in the method body, but if you use it in combination with the if statement, you can write code like the following:

if( x == -1)
{
  return -1;
}
else
{
  return 0;
}

This code specifies the return value depending on some other test; actually, you will use it with methods that call Stored Procedures to specify the return value from the data tier to the business tier. Let’s take an example of returning a value other than void:

using System;
namespace MyCompany
{
  public class Loops
  {
    static void Main(string[] args)
    {
      Console.WriteLine(“Enter a number”);
      int temp = TestNumber(Convert.ToInt32(Console.ReadLine()));
      if(temp == 1)
      {
        Console.WriteLine(“This is an EVEN number”); 
      }
      else
      {
        Console.WriteLine(“This is an ODD number”);
      } 
      Console.ReadLine(); 
    } 

    static int TestNumber(int x) 
    {
      if(x % 2 == 0)
      {
        return 1;
      }
      else
      {
        return 0; 
      } 
    } 
  }
}

 
The return statement has been used to return 1 in the case of an even number and 0 in the case of an odd number. The return value has been assigned to a local variable of the Main method. Note that the compiler can do an implicit conversion of the return value in order to return a value of the method’s return value so you can’t return a string while the method return value is an integer.

{mospagebreak title=break and continue statements}

The break statement breaks the execution of the current statement block and executes the first line that follow the block. Usually you will find code like this:

static void Main(string[] args)
{
  int x = 0;
  for(;;)
  {
    x = Convert.ToInt32(Console.ReadLine());
    if(x == -1)
      break; 
    else
      Console.WriteLine(“It’s ” + x);
  }
  Console.WriteLine(“Program exist”);
}

The code is simply an infinite for loop (infinite for loops constructed using empty expressions for all the parts as you can see), and inside the loop we use an if statement to test if the input number is -1; if so,  the for loop breaks, and execution begins at the first line after the for loop. You can check the message “Program exist” using CTRL + F5. The above code can be written using the while statement as follows:

static void Main(string[] args)
{
  int x = 0;
  while(true)
  {
    x = Convert.ToInt32(Console.ReadLine());
    if(x == -1)
      break;
    else
      Console.WriteLine(“It’s ” + x);
  }
  Console.WriteLine(“Program exist”);
}

As you can see, the for(;;) loop is the same as while(true), but you need to use the break statement, or maybe your algorithm needs the goto statement in order to terminate the execution of the infinite loop, and continue on the first statement after the loop. As we saw before,  the break statement’s primary use is with the switch statement, so I will not discuss it again. Before we end our discussion about the break statement, I want to distinguish between break and goto through code. Consider the following code:

static void Main(string[] args)
{
  for(;;)
  {
    Console.WriteLine(“Enter a word”);
    string temp = Console.ReadLine();
    Char[] tempChar = temp.ToCharArray();
    foreach(Char x in tempChar)
    {
      if(x == ‘h’)
        break;
      else
        Console.WriteLine(x);
    }
  }
}

This code takes a word from the user and writes every character in the word in a separate line. If the character is ‘h’, it breaks using the break statement. Now enter the following words and see what will happen: “Michael” then “Mic” then “h”. Some of you will think that whenever the program encounters the ‘h’ it will terminate because of the break statement; the result is the following:

As you can see, in the first word “Michael” the program prints only the characters before the character ‘h'; in the second word “Mic” it prints all the characters; and in the third word (which is only the letter h) it will print nothing. Guess what? The loop is still here and the program didn’t terminate. All of this happens because the break statement breaks only the current block, which in our case is the inner foreach block. So when it breaks the foreach loop, the infinite for loop iterates again and again, and it will never end. One perfect solution for this problem involves using the goto statement as follows:

static void Main(string[] args)
{
  for(;;) 
  {
    Console.WriteLine(“Enter a word”);
    string temp = Console.ReadLine();
    Char[] tempChar = temp.ToCharArray();
    foreach(Char x in tempChar)
    {
      if(x == ‘h’) 
        goto exist;
      else
        Console.WriteLine(x);
    }
  }

  exist:
    Console.WriteLine(“the Program is terminating”);
}

You will get the following result, as expected:

This is one perfect use for the goto statement, where the break statement is not appropriate at all.

C# features another keyword that must be discussed with the break statement; it’s the continue statement. As you know, the break statement breaks the execution of the current loop and begins execution on the first line after the current loop. The continue statement differs from the break statement because it will not break the execution of the current loop; instead it will terminate the current iteration and begin a new iteration in the loop. In other words, the continue statement, when encountered in the loop, will escape the next statements in the iteration and go to the top of the loop to CONTINUE looping. Here is the same example as I used above, this time with continue instead of break and goto:

static void Main(string[] args)
{
  for(;;)
  {
    Console.WriteLine(“Enter a word”);
    string temp = Console.ReadLine();
    Char[] tempChar = temp.ToCharArray();
    foreach(Char x in tempChar)
    {
      if(x == ‘h’)
        continue;
      else
        Console.WriteLine(x);
    }
  }
}

Enter the word “Michael” and the see the result:

What happened is that the program actually escaped the character ‘h’ and continued printing all the other characters without terminating the loop. As I said before, each statement fits inside a specific scenario, so use the continue statement when you need to escape a number of statements without the loop termination.

[gp-comments width="770" linklove="off" ]