Branching Statements (if, else, switch)

 

 if

 

The first type of branching statement we will look at is the if statement. An if statement has the form:

if( expression/condition )
     statement

where expression is any expression and statement is any statement.

 

What if you have a series of statements, all of which should be executed together or not at all depending on whether some condition is true? The answer is that you enclose them in braces:

     if( expression )
            {
	statement_1
	statement_2
	statement_3
             }

As a general rule, anywhere the syntax of C calls for a statement, you may write a series of statements enclosed by braces. (You do not need to, and should not, put a semicolon after the closing brace, because the series of statements enclosed by braces is not itself a simple expression statement.)

 

An if statement may also optionally contain a second statement, the ``else clause,'' which is to be executed if the condition is not met. Here is an example:

	if(n > 0)
		average = sum / n;
	else	{
		printf("can't compute average\n");
		average = 0;
		}

The first statement or block of statements is executed if the condition is true, and the second statement or block of statements (following the keyword else) is executed if the condition is not true. In this example, we can compute a meaningful average only if n is greater than 0; otherwise, we print a message saying that we cannot compute the average. The general syntax of an if statement is therefore

	if( expression )
		statement(s) if the condition is true
	else
		statement(s) if the condition is false

In an if statement, condition is a value or an expression that is used to determine which code block is executed, and the curly braces { }act as "begin" and "end" markers.

 

Here is a full C++ program as an example:

 

#include <stdio.h>

int main() {
  // define two integers
  int x = 3;
  int y = 4;

  //print out a message telling which is bigger
  if (x > y) {
    printf("x is bigger than y" );
  }
  else {
    printf("x is smaller than y");
  }
  return 0;
}

In this case condition is equal to "(x > y)" which is equal to "(3 > 4)" which is a false statement. So the code within the else clause will be executed. The output of this program will be:

 

x is smaller than y

If instead the value for x was 6 and the value for y was 2, then condition would be "(6 > 2)" which is a true statement and the output of the program would be:

 

x is bigger than y

It's also possible to nest one if statement inside another. (For that matter, it's in general possible to nest any kind of statement or control flow construct within another.) For example, here is a little piece of code which decides roughly which quadrant of the compass you're walking into, based on an x value which is positive if you're walking east, and a y value which is positive if you're walking north:

 

if(x > 0)
   {
        if(y > 0)
           printf("Northeast.\n");
        else printf("Southeast.\n");
    }
else

     {
        if(y > 0)
            printf("Northwest.\n");
        else printf("Southwest.\n");
}

 

When you have one if statement (or loop) nested inside another, it's a very good idea to use explicit braces {}, as shown, to make it clear (both to you and to the compiler) how they're nested and which else goes with which if. It's also a good idea to indent the various levels, also as shown, to make the code more readable to humans. Why do both? You use indentation to make the code visually more readable to yourself and other humans, but the compiler doesn't pay attention to the indentation (since all whitespace is essentially equivalent and is essentially ignored). Therefore, you also have to make sure that the punctuation is right.

 

 switch

 

The next branching statement is called a switch statement. A switch statement is used in place of many if statements.

 

Let's consider the following case: Salman is writing a program that figures interest on money that is held in a bank. The amount of interest that money earns in this bank depends on which type of account the money is in. There are 6 different types of accounts and they earn interest as follows:

 

account type

interest earned

personal financial

2.3%

personal homeowner

2.6%

personal gold

2.9%

small business

3.3%

big business

3.5%

gold business

3.8%

 

One way for Salman to write this program is as follows: (assuming also that Salman has assigned numbers to the account types starting with personal financial and ending with gold business.)

 
// declare a variable to keep track of the interest
float interest = 0.0;

// decide which interest rate to use.
if (account_type == 1){
  interest = 2.3;
  }
else {
     if (account_type == 2) {
       interest = 2.6;
       }
     else {
          if (account_type == 3){
            interest = 2.9;
            }
          else {
               if (account_type == 4){
                 interest = 3.3;
                 }
               else {
                    if (account_type == 5){
                      interest = 3.5;
                      }
                    else {
                         // account type must be 6
                           interest = 3.8;
                         }
                    }
               }
          }
     }

 

 

That code is hard to read and hard to understand. There is an easier way to write this, using the switch statement. The preceding chunk of code could be written as follows:

 

 

switch (account_value){
  case 1:
	interest = 2.3;
	break;
  case 2:
	interest = 2.6;
	break;
  case 3:
	interest = 2.9;
	break;
  case 4:
	interest = 3.3;
	break;
  case 5:
	interest = 3.5;
	break;	
  case 6:
	interest = 3.8;
	break;
  default:
	interest = 0.0;
}

 

The switch statement allows a programmer to compound a group of if statements, provided that the condition being tested is an integer. The switch statement has the form:

 
switch(integer_val){
   case val_1:
      // code to execute if integer_val is val_1
      break;
    ...
   case val_n:
      // code to execute if integer_val is val_n
      break;
   default:
      // code to execute if integer_val is none of the above
}

 

The default clause is optional, but it is good programming practice to use it. The default clause is executed if none of the other clauses have been executed. For example, if my code looked like:

switch (place) {
   case 1:
      cout << "we're first" << endl;
break;
   case 2:
      cout << "we're second" << endl;
break;
   default:
cout << "we're not first or second" << endl;
}
 

This switch statement will write "we're first" if the variable place is equal to 1, it will write "we're second" if place is equal to 2, and will write "we're not first or second" if place is any other value.

 

The break keyword means "jump out of the switch statement, and do not execute any more code." To show how this works, examine the following piece of code:

int value = 0;
switch(input){
  case 1:
    value+=4;
  case 2:
    value+=3;
  case 3:
    value+=2;
  default:
    value++;
}

If input is 1 then 4 will be added to value. Since there is no break statement, the program will go on to the next line of code which adds 3, then the line of code that adds 2, and then the line of code that adds 1. So value will be set to 10! The code that was intended was probably:

 
int value = 0;
switch(input){
  case 1:
    value+=4;
    break;
  case 2:
    value+=3;
    break;
  case 3:
    value+=2;
    break;
  default:
    value++;
}
 

This feature of switch statements can sometimes be used to a programmers' advantage. In the example with the different types of bank accounts, say that the interest earned was a follows:

 

account type

interest earned

personal financial

2.3%

personal homeowner

2.6%

personal gold

2.9%

small business

2.6%

big business

2.9%

gold business

3.0%

 

Now, the code for this could be written as:

switch (account_value){
  case 1:
    interest = 2.3;
    break;
  case 2:
  case 4:
    interest = 2.6;
    break;
  case 3:
  case 5:
    interest = 2.9;
    break;
  case 6:
    interest = 3.8;
    break;
  default:
    interest = 0.0;
}