Lecture 5: Selection via the if Statement

So far we have written only simple program, in the sense that the computer started working on the first instruction in the main function, and then continued to work in sequence on the remaining one until it encountered the return statement.

Usually, however, we need to get our program to make choices based on the result of some user action or on a particular computation that the computer has performed. C++ offers the if statement for exactly that purpose.

if Statement, Basic Version

The if statement, in it's simplest form, allows you to conditionally execute a statement or group of statements in case a certain condition has been met. The syntax is as follows:

   if (test)
      statementBlock;

where

test is a logical test enclosed in simple parenthesis
statementBlock is either a single statement, or a group of statements enclosed between the grouping symbols { ... }

Before we can look at any examples, we need to know how to write a test condition for the if statement. Comparison Operators

C++ provides the standard comparison operators to compare its basic data types as follows:

Operator Meaning Description
== equal A == B is true if A and B have the same value
!= not equal A != B returns true if A and B do not have the same value
> greater than A > B returns true if the value of A is greater than the value of B
>= greater than or equal to A >= B returns true if the value of A is greater than or equal to the value of B
< less than A < B returns true if the value of A is less than the value of B
<= less than or equal to A < B returns true if the value of A is less than or equal to the value of B

NOTE: Since C++ does not have a special data type to indicate true or false it substitutes a value of 0 to indicate false and a value different from zero (usually 1) to indicate true

NOTE: The operator to test for equality is ==, not just =. Recall that = is already the assignment operator. Using a single equality when your intentions are to test for equality is a very common error in the initial versions of your programs. This error is often difficult to spot, since some compilers do not consider it a syntax error.

In addition, C++ provides three logical operators as follows:

Operator Meaning Description
&& and ((A) && (B)) returns true if both A and B are true
|| or ((A) || (B)) returns true if either A or B or both are true
! not (!(A)) returns true if A is not true (i.e. if A is false)

You can use any amount of simple parenthesis to combine statements using the above logical operators.

Now we are ready for some examples using the simple if statement.

Example: Write a program that displays "yes" on the screen if a number entered by a user is positive.

Leaving out the usual #<iostream.h&g; which must almost always be present, our program looks as follows:

int main(void)
{
   double x; // number to be entered
   cout << "Enter a number: ";
   cin >> x;

   if (x > 0)
      cout << "yes";
   return 0;
}

In this example, though, we might also want to find out what happens when the input value is not positive, i.e. we want the computer to say either "yes" or "no", depending on whether the value is positive or not.

Our first approach would be a program like this:

int main(void)
{
   double x; // number to be entered
   cout << "Enter a number: ";
   cin >> x;

   if (x > 0)
      cout << "yes";
   cout << "no";
   return 0;
}

However, that program would be logically wrong:

If the input value is, say, -10, then the statement inside the if will not execute, but the statement following it will, producing the correct answer "no"
If the input value is, say, 10, then the statement inside the if will execute, producing "yes". But then, also the next statement will execute, producing "no". In other words, in this case the computer will display both "yes" and "no" - that's not right.

To fix the mistake, we could construct a program like this:

int main(void)
{
   double x; // number to be entered
   cout << "Enter a number: ";
   cin >> x;

   if (x > 0)
      cout << "yes";
   if (x <=0)
      cout << "no";
   return 0;
}

Now the program will work correctly, but C++ actually offers a shortcut for this.

if Statement with Alternative

The if statement with alternative allows your program to decide between two disctinct options. The syntax is as follows:

   if (test)
      statementBlock1;
   else
      statementBlock2;

where

test is a test as before
statementBlock1 is a statement, or block of statements enclosed in grouping symbols, that will execute if the test returns true
statementBlock2 is a statement, or block of statements enclosed in grouping symbols, that will execute if the test returns false

Example: Create a program that says "yes" if an input number is positive, and "no" if it is not.

Using the if with alternative, your program would look as follows:

int main(void)
{
   double x;   // the input number;
   cout << "Enter a number:";
   cin >> x;
  
   if (x > 0)
      cout << "yes";
   else
      cout << "no";
   return 0;
}

What, though, if we wanted to decide between three or more alternatives ?

Nested if Statements

The previous versions of the if statements can be "nested" to any level. In other words, you can have if statements inside other if statements inside other if or else statements, and so on.

If you use nested if statements, it is sometimes hard to understand the logic of all combined statements. There are two rules to consider:

Every else always belongs to the closest if
When using nested if statements, use grouping symbols to remove any ambiguity
While indentation has no effect on the compiler, you should always use the appropriate level of indentation so that it is clear at a glance where one if statement starts and another one ends.

Example: Create a program that states whether an input number is positive, negative, or zero.

Clearly, I have more than two options, so a single if statement will not work. Instead, I use a nested if construction as follows:

int main(void)
{
   double x;   // the input number
   cout << "Enter the number: ";
   cin >> x;

   if (x == 0)
      cout << "is zero";
   else
      if (x > 0)
         cout << "is positive";
      else
         cout << "is negative";
   return 0;
}

While this program is correct, I would use grouping symbols to make it clear which else belongs to what if (actually, for the compiler the rule is that the closest if counts, but I would use grouping statements to make it clear for humans as well). In other words, I would revise the test as follows:

   if (x == 0)
      cout << "is zero";
   else
   {
      if (x > 0)
         cout << "is positive";
      else
         cout << "is negative";
   }

Note that this is, as far as the compiler is concerned, exactly the same as the previous test. However, for "humans" it makes it more readable, so this option is the preferred one.

Nested if statements can quickly get very confusing, so C++ offers a shortcut:

if with Multiple Alternatives

To construct a test that can handle any number of alternatives, one can often use the following syntax:

   if (test1)
      statementBlock1;
   else if (test2)
      statementBlock2;
   else if (test3)
      statementBlock3;
   ...
   else
      statementBlockN;

where

statementBlock1 will execute if test1 is true
statementBlock2 will execute if test1 is false and test2 is true
statementBlock3 will execute if test1 and test2 are both false, and test3 is true
... and so on ...
statementBlockN (the last one) will execute if all previous tests return false

Example: Suppose we want to create a program that takes as input a grade in percent, and produces as output a letter grade. We can assume the "standard" cut-off points.

The program clearly has multiple choices to make:

if the percent is between 90 and 100, assign A
if the percent is between 80 and 90, assign B
if the percent is between 70 and 80, assign C
if the percent is between 60 and 70, assign D
if the percent is less than 60, assign F

While we could use nested if statements, it would be better to try if with multiple alternatives, as follows:

int main(void)
{
   double x;
   cout << "Enter the grade in percent: ";
   cin >> x;

   if ( (x >= 90) && (x <= 100))
      cout << "A";
   else if ( (x >=80) && (x < 90))
      cout << "B";
   else if ( (x >=70) && (x < 80))
      cout << "C";
   else if ( (x >=60) && (x < 70))
      cout << "D";
   else if (x < 60)
      cout << "F";
   return 0;
}

Note that we have used the and operator && to combine the various tests for the percentage grade. BUT, this program not only looks very complicated, it also is an example of bad programming: we are not really using the if with multiple alternatives correctly.

First, the number x represents percentage, and therefore can not be larger than 100. We should thus not have to test for x being bigger than 100.

Secondly, and more importantly, the only way the second statement (assigning a "B") can happen, is if the first test returns false. In other words, the only way the second test can be reached is if the grade in percent is not 90 or better. Hence, I don't have to test again whether the grade is less than 90 - I know it must be, because otherwise this statement would never be reached.

Therefore, we should rewrite the test as follows:

   if (x >= 90)
      cout << "A";
   else if (x >=80)
      cout << "B";
   else if (x >=70)
      cout << "C";
   else if (x >=60)
      cout << "D";
   else
      cout << "F";     

Note also that we completely removed any test for the last else. After all, the only possibility of reaching this line is if every previous test has failed, which means that the grade percentage is less than 60% for sure; we don't have to test for this again.

When using multiple if and else statement, one has to be somewhat careful about the order that the tests are made. For example, we could not use the following test for our program:

   if (x >=60)
      cout << "D";
   else if (x >=70)
      cout << "C";
   else if (x >=80)
      cout << "B";
   else if (x >= 90)
      cout << "A";
   else
      cout << "F";

This would be incorrect ... what, for example, would the grade be if somebody had a 92% ?

(bgw)