If-Else Statement

download the slides used in this presentation
PowerPoint pptx | Acrobat pdf

Objectives

While engaging with this module, you will...

  1. learn what it means to branch
  2. extend your knowledge of comparison statements to perform simple branching operations
  3. find out what it means to exit

Branching

To this point in your study of C++, you have only learned enough to write rather simple programs. You have the capability to input, output, remember, and modify data. To complete the ability to compute anything that is computable, you need the ability to do decision branching and looping. We address the former here, and the later in another lesson of this course.

The if-else Statement

The if-else statement allows a program to take one of two branches or paths of execution depending on the value of some expression. That expression can be very simple or very complex, but quite naturally it is a changing value. I will give you a general statement of the syntax, and then explain the parts.

if (expression)
    statement1
else
    statement2

And here are the particulars:

Warning! Don’t put a semi-colon after the closing paren. If you do, the compiler reads that as terminating the if-else statement. You will get a compile error because you then have an else without an if.

Let's look at some examples.

// EXAMPLE #1
if (4)                   // this is a ridiculous example since the expression, 4, is a
        cout<<”hello”;   // constant value equivalent to true; the cout statement
                         // is always executed

// EXAMPLE #2
cout<<"enter radius: ";  // prompt for and read in radius of circle
cin>>radius;
if (radius <= 0)         // looking for invalid input!
{
      cout<<"Error: no circle has non-positive radius!"<<endl; // not a circle
      exit(1);
}
area = PI * radius * radius;     // calculate area
cout<<"The circle with radius "<<radius<<" has area "<<area<<"."<<endl;
cout<<"Ending this example..."<<endl;  // rest of program

// EXAMPLE #3         (re-coding of EXAMPLE 2)
cout<<"enter radius: ";  // prompt for and read in radius of circle
cin>>radius;
if (radius <= 0)         // looking for invalid input!
      cout<<"Error: no circle has non-positive radius!"<<endl; // not a circle
else                     // valid input
{
    area = PI * radius * radius;     // calculate area
    cout<<"The circle with radius "<<radius<<" has area "<<area<<"."<<endl;
}
cout<<"Ending this example..."<<endl;  // rest of program

In the first example, the expression is always true and the cout statement is ALWAYS executed. This is not useful at all. In the second example, if the expression in the if is true, then bad input has been detected and an error message is output before the execution of the program is prematurely terminated using the exit function. This will be explained below. In the third example, a better way to handle the bad input is shown.

Notice the use of the compound statement under the else clause to execute more than one statement in this case. Also notice the indentation of TWO spaces (don’t use tabs). This makes the code readable. Be consistent with your indentation for maximum readability.

This next example demonstrates what I call an eSieve. The input percolates down through the code and the appropriate assignment is made. We suppose that all variables are declared, etc...

const int MAX_A = 100;
const int MIN_A = 90;
const int MIN_B = 80;        //etc. I leave out the rest for space considerations

cout<<”enter average: “;
cin>>ave;

if (ave > MAX_A)
    cout<<”Error: average out of range!”<<endl;
else
    if (ave >= MIN_A)
        grade = ‘A’;
    else
        if (ave >= MIN_B)
            grade = ‘B’;
        else
            if (ave >= MIN_C)
                grade = ‘C’;
            else
                grade = ‘F’;  // stopped here since the point has been made

Thus, if ave is out of range, an error message is output. Otherwise (hits the first else – ave less than 100), we check to see if 90 <= ave (and we already KNOW ave <= 100). If so, assign the character variable grade the value ‘A’. If not, check to see if ave >= 80 (and we already KNOW ave < 90). If so, assign grade the value of ‘B’. And so on. It is important to notice that no (expression) is necessary following the else. Why? Well, you must remember that the if-else partitions the action space into two distinct possibilities. Thus, if the expression is false, then there is NO other decision to be made; it’s either one way or the other way.

You will also notice that, if this pattern continues, the code will walk off the screen! An acceptable alternative format is given by:

cin>>ave;

if (ave > MAX_A)
    cout<<”Error: average out of range!”<<endl;
else if (ave >= MIN_A)
    grade = ‘A’;
else if (ave >= MIN_B)
    grade = ‘B’;
else if (ave >= MIN_C)
    grade = ‘C’;
else if (ave >= MIN_D)
    grade = ‘D’;
else if (ave >= 0)
    grade = ‘F’;
else
    exit(3);    // explained in the next section

This format is syntactically the same as the other; it’s just that it is formatted differently for a person reading it, and avoids the “walking off the page” problem. Always remember, the compiler doesn’t read like a human does. Formatting matters not a bit to a compiler. The formatting of your code is for people (could be you) reading the code for purposes of understanding, upkeep, modification, etc.

The exit Function

Here we are getting a little ahead of ourselves in that we’re going to take a little tangent to look at exit. This topic involves using functions, which we won’t cover in detail in the course for several more lessons yet. However, the use of this particular function can be introduced without confusion.

The motivation is this: suppose something occurs during the run of the program that your code is unable to handle? What then? If you take more advanced courses covering advanced topics in C++ you will about "exception handling". This is a standard C++ way of handling such situations. But, in lieu of that method, we can employ a system function that will gracefully terminate the execution of the program. Let’s begin with an explanation of the "return 0;" statement at the end of main.

When the return 0; statement is executed, the value 0 is sent to the operating system, signaling the successful completion of the program. Other values that might be sent to the OS can signal other conditions, such as an unsuccessful completion, and particular error conditions. Normally, there should be only one return statement in the main function.

The exit function is built into the compiler. When it is executed, all the necessary "cleaning up" after your program is done and the value you designate to be sent by exit is sent to the OS. Cleaning up? Yes, there is a lot of overhead incurred in your program that you don’t normally deal with: allocating memory for variables, setting up of function tables, etc. When your program terminates, all this overhead should be dismantled properly and the exit function will do that. Value sent? Yes, here’s how it works: the statement exit(3); sends the value 3 back to the OS. In this example, 3 is the argument that fills a function parameter. For exit, that parameter is an int. Different integer values can be used to mean different error conditions. For example, you might send 1 back to the OS to indicate the user didn’t input the right type of value. You might send 2 back to the OS to indicate a malfunctioning piece of hardware. Etc.

This is not a function that you will use much, but there it is if you feel the need. In the example above, I used it to demonstrate its use. In reality, the value less than zero for the variable average should never have happened in the first place.

When we learn looping, I will demonstrate another good use for the exit function.

Course Menu
0. Getting Started
0.0. Welcome
1. The Big Picture
2. Programming Fundamentals
3. Operators
4. Branching
5. Loops
6. Advanced Branching
7. Odds and Ends
8. Functions
9. Random Number Generation
10. Multiple Files
11. Arrays
12. Structs
13. Character Arrays
14. File I/O
15. Objects
16. Output Formatting
16.0. Overview
17. Namespaces
18. Enumerations
19. Sample Homework