Branching and Looping in C#, Part 1

Certainly you are familiar with if, switch, while, return and goto statements. These are famous Branching and Looping statements in many programming languages for selecting code paths conditionally, looping and jumping to another part of your application unconditionally. In this article we will discuss what C# offers to us from these statements. As you will see, the common programming errors that existed in C++ were eliminated with C# statements.

The if Statement

The if statement gives you the ability to test an expression, then select a statement or a group of statements to be executed if the expression evaluates to true. If you have the else part of the statement, you can execute another statement (or statements) if the expression evaluates to false. The syntax of if statement is as follows:

if(bool expression)
statement 1;

As we will see shortly, the expression must evaluate to bool value (true or false). If you have more than one statement, you must put the statements in a block using curly braces:

if(bool expression)
{
  statement 1;
  statement 2;
  statement 3;
}

The same applies to the else statement, so if you have only one statement to execute with the else statement, you can write it like this:

if(bool expression)
  statement 1;
else
  statement 1;

But if you have multiple statements in your else part, you can write it as:

if(bool expression)
{
  statement 1;
  statement 2; 
  statement 3;
}
else
{
  statement 1;
  statement 2;
  statement 3;
}

For consistency, use the curly braces even if you have only one statement with the if statement or with the else statement. Most programmers prefer this usage.

{mospagebreak title= No Implicit Conversion} 

C# eliminates a common source of programming errors that existed in the world of C and C++, which is the implicit conversion of numeric values to Boolean values (0 to false and all the other numeric values to true). In C#, the if statement’s expression must evaluate to a Boolean value, so the next block of code will not compile in C# but it will compile in C++:

int x = 10;
if(x)
{
  Console.WriteLine(x);
}

In C# you will get a compile time error that states ”Can’t implicitly convert type ‘int’ to ‘bool’”. You need to write this block as follows:

int x = 10;
if(x > 5)
{
  Console.WriteLine(x);
}

This will compile in C# because now it’s a Boolean expression. Let’s look at an example. The following example takes an input number from the user, tests to see if it’s an even or odd number (using the module operator), and prints a line in each case.

using System;
namespace MyCompany
{
  public class IfStatement
  {
    static void Main(string[] args)
    {
      Console.WriteLine(“Please type a number”);
      int x = Convert.ToInt32(Console.ReadLine());
      if(x % 2 == 0)
      {
        Console.WriteLine(“this is an EVEN number”);
      }
      else
      {
        Console.WriteLine(“this is an ODD number”);
      } 
      Console.ReadLine(); 
    } 
  } 
}
 

{mospagebreak title=Nesting}

Of course you can nest if statements as much as you want. Let’s take a look:

using System;
namespace MyCompany 
{
  public class IfStatement
  {
    static void Main(string[] args)
    {
      Console.WriteLine(“Please type a number”);
      int 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”);
        } 
      }
      Console.ReadLine(); 
    }
  }
}

As you can see, I have added nested if statements to test if the number is greater than or less than 1000, and I print to the console a line in each case. One thing to note about VS.NET is its indentation scheme:

You can tell that there’s only one top level if statement associated with an else statement, and each statement has a nested if statement, too. VS.NET will indent if statements automatically.

{mospagebreak title=Combining else With if} 

You can combine else with if in one statement to execute more than one test on the expression. As you already know, if tests the expression, and if it evaluates to false, the else block will be executed. Sometimes this is not what we need, however. We may need to be very specific with the else part. For example, take a look at the following code:

int x = 5;
if(x != 0)
{
  Console.WriteLine(“x != 0″);
}
else
{
  Console.WriteLine(“x = 0″);
}

There is nothing special about this code; but notice that with the if statement we test to see if the x is not equal to zero, and if so, it will execute the if block, and else it will execute the else block. Now let’s look at the following code:

using System;
namespace MyCompany
{
  public class IfStatement
  {
    static void Main(string[] args)
    {
      int x = 5;
      if(x == 0)
      { 
        Console.WriteLine(“x != 0″); 
      }
      else if(x == 4)
      {
        Console.WriteLine(“x == 4″); 
      } 
      else if(x == 5)
      {
        Console.WriteLine(“x == 5″);
      }
      else
      {
        Console.WriteLine(“x = 0″); 
      }
      Console.ReadLine(); 
    } 
  }
}
 

if you compile and run the application, you will get the following in the console window:

C# features the combination of else with if to further test the Boolean expression (only when the if statement evaluates to false), so if the if Boolean expression evaluated to true, the else if statements will never be tested. I will rewrite the above code as follows:

using System;
namespace MyCompany 
{
  public class IfStatement
  {
    static void Main(string[] args)
    { 
      int x = 5;
      if(x != 0)
      {
        Console.WriteLine(“x != 0″);
      }
      else if(x == 4)
      {
        Console.WriteLine(“x == 4″);
      }
      else if(x == 5)
      {
        Console.WriteLine(“x == 5″);
      }
      else
      {
        Console.WriteLine(“x = 0″);
      } 
      Console.ReadLine(); 
    }
  }
}

You will get the following result:

This is an unexpected result, because x is assigned 5. It is true that x is assigned 5, but the code was not perfect; the if statement tested to check if x is not equal to 0, and it’s not equal to zero, so it escaped  the next else if statement, and that’s why we got this value. With this in mind, never use an expression that is misleading while using else if statements.

{mospagebreak title=The switch Statement}

The switch statement is similar to multiple else if statements, but it accepts only expressions that will evaluate to constant values. The if/else structure is appropriate for small groups of Boolean expressions, but it would be very ugly to write 20 else if statements to test for some values: else if(x ==5) do something else if(x == 6) do another thing, and so on. This is the syntax of a switch statement:

switch(expression)
{
  case constant-value:
    statement 1;
    statement 2;
    jump statement
  case constant-value:
    statement 1;
    statement 2;
    jump statement
  default:
    statement 1;
    statement 2;
    jump statement
}

There are more than three keywords you can use with the switch statement: first, the switch keyword which, followed by an expression that returns an integral value of type sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an Enumeration value. The switch expression’s value can be returned from a method call, too.

After the switch expression is evaluated, the value will be compared to each case label, and when the value is found, control is transferred to the first statement in the this case statement. Each case statement must be ended with a jump statement (unlike C and C++), such as break or goto. The case keyword is used to define a constant value (called case label) that will be compared to the value returns from the switch expression. The constant value of the case label must have a compatible value with the switch block. This makes sense, because you can’t define an int case label while the switch expression returns a string value. We will talk about jump statements later in the article.

The default keyword declares the default statement, which will be executed if none of the case labels match the switch expression. There can be only one default statement for each switch statement, and you can write your switch statement without a default statement, too. Let’s take a look at an example of a switch statement with our famous Employee class example:

using System;
namespace MyCompany
{
  public enum Jobs
  {
    Programmer = 1,
    NetworkAdmin = 2,
    Designer = 3,
    COMDeveloper = 4
  }

  public class Employee
  {
    public Positions EmpJob;

      // class constructor
      public Employee(Jobs EJ)
      {
        switch(EJ)
        {
          case Jobs.Programmer:
            Console.WriteLine(“You are a programmer”);
            break;
          case Jobs.NetworkAdmin:
            Console.WriteLine(“You are a network administrator”);
            break;
          case Jobs.Designer:
            Console.WriteLine(“You are a designer”); 
            break;
          default: 
            Console.WriteLine(“You are an employee”); 
            break; 
        }
      } 
  }

  public class EmployeeTest
  {
    static void Main(string[] args)
      {
        Employee Michael = new Employee(Jobs.Designer);
        Console.ReadLine();
      }
  }
}
 

This is a very simple example. The Employee class constructor accepts a value of type Positions, and defines a switch case block to print the Employee job title. One very important issue to notice is that, with the if/else structure you can write as many else if statements, each with different conditional expressions, as you want – but you can’t do that with the switch/case structure. Here the case statements just test for the value of the switch expression, and if the comparison succeeds, the block get executed. If you have a statement that will be executed with more than one case label, you can combine case labels in the following way:

switch(EP)
{
  case Positions.Programmer:
  case Positions.NetworkAdmin:
  case Positions.Designer:
    Console.WriteLine(“You are an IT Employee”);
    break;
  default:
    Console.WriteLine(“You are an employee”);
    break;
}

You simply write a case statement followed by the next, until you write them all; then write the statement you want to be executed, then a jump statement. In C# you must use jump statements between case statements, because the designers of C# eliminated the fall though that has been in C and C++. You can still explicitly state that you need the functionality of fall though by using the goto jump keyword:

switch(EP)
{
  case Positions.Programmer:
    goto case Positions.Designer;
  case Positions.NetworkAdmin:
    goto case Positions.Designer;
  case Positions.Designer:
    Console.WriteLine(“You are an IT Employee”);
    break;
  default:
    Console.WriteLine(“You are an employee”);
  break;
}

This is an explicit fall through that is clear for every programmer and in fact this technique eliminates the common problems associated with fall through.

{mospagebreak title=Looping Statements}

Executing a statement (or a group of statements) a number of times is called looping, and there are four statements for looping and iteration in C#, so let’s begin with the for statement.

The for Statement

This is the famous for loop structure that many of you have been using to write your own algorithms. The for loop is used when the number of loops is known (unlike the while loop, as we will see later). The syntax of the for loop is:

for (initialization; conditional expression; stepping)
{
  statement 1;
  statement 2;
}

As you can see, the initialization, the expression that controls the loop, and the stepping parts are all defined in the top of the statement and in one location. The parts are also separated by semicolons, and you begin the looped statements, or the statements that will be executed in the loop, using a block ( { } ). The first part of the for statement is the initialization part; use this part to initialize the variables that will be used in the algorithm of the for loop. Note that these variables are allocated on the stack, and this part will be executed only one time, because it doesn’t make any sense to declare and initialize the same variable with the same value each time in the loop.

The next part is the conditional expression, which determines whether the loop will be executed again or not. If the condition (something like i < myArray.Length) evaluated to false, control passes to the first statement after the for statement block. If the condition evaluated to true, the body of the for block (the controlled statements) will be executed.

The last part is the stepping part. Usually it will be a counter that will increment the variable that the conditional expression uses, because at some point we need the conditional expression to evaluate to false and terminate the execution of the for loop. Note that the stepping part executes after the controlled statements. That is, first the initialization part executes (one time only) and the variables allocate space on the stack; second, the conditional expression is evaluated, and if true, the controlled statements execute, followed by the stepping part execution, and again the conditional expression is evaluated and the process iterates.

Note that any of the three parts that make the for statement can be empty; although it’s not common, it can happen. Take a look:

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

Compile the method into a class and run the application; you will get the following result:

As you can see, we omit the initialization part and we just put in the semicolon. Also note that the counter can increment or decrement, and it’s up to you to define the algorithm.

The for loop can be used to define very complex algorithms; this happens as a result of nesting the for loops. Let’s take a very simple example which extends the above loop example. It will simply write the same numbers, but this time with a little difference.

public class Loops
{
  static void Main(string[] args)
  {

    for(int x = 10; x < 100; x += 10)
    {
      Console.WriteLine();
      Console.WriteLine(x);
      for(int y = x – 1, temp = x – 10; y > temp; y–)
      { 
        Console.Write(“{0}, “, y);
      }
    }
    Console.ReadLine();
  }
}

Compile the class and run it, and you will get the following result:

I have used a nest for loop to print all the numbers between two iterations from the outer for loop. The ability to use for loops actually makes great programmers.

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