Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 5: Decision Structures

Decision Structures

if-else structures

  • An if-statement is a way to have your program make a choice based upon a condition. It is an either-or decision structure, with no repetition. Here’s the format:
          if( <condition> )
          {
            <result 1>;
          }
          else
          {
            <result 2>;
          }

    In the above example, <result 1> represents code which is executed only if the <condition> is true. If it’s false, <result 2> is executed instead. The curly braces are only needed for results that contain more than one line of code.

  • The else-clause is optional. So the following as allowed as well:
          if( <condition> )
          {
            <result 1>;
          }

    In the above format, if <condition> is false, <result 1> is not executed, and the code continues after the closing curly brace (or after the semi-colon if there are no curly braces).

  • With all if and if-else statements, whether or not the condition is true, the code always continues after the if structure is finished.
  • Notice the placement of semi-colons above.
  • Remember that indentation reflects the level, or scope, of a line of code.
  • The result/body of an if-statement or else-statement is always indented a bit more than the surrounding code.

Relational Operators

  • Use
    1
    ==

    for equality comparison! (assignment operator “=” changes the value on the left, instead of checking to see if values are equal)

  • 1
    &lt;

    means less than

  • 1
    &lt;=

    means less than or equal to

  • 1
    &gt;

    means greater than

  • 1
    &gt;=

    means greater than or equal to

  • 1
    !=

    means not equal

Here’s a program uses the above structures to calculate interest on an investment

In-class exercise: Write a program to input the ages of 2 people. Then output if the ages are the same or not.

ages.java: Solution to above in-class exercise

Nested and Multi-Way If-Statements

  • Like most other structures, if-statements may be nested, meaning one if-statement may be put inside another. Beware of dangling else-statements in such structures. For example:
        int age = 17;
        if (age >= 18)
          if (age <= 65)
            cout << "working age";
          else
            cout << "not working age";

    What will be output by the above code? Else-statements always go with the most recent if-statement in their block, so the else applies to situations where age is over 65 only. No output is produced. To make the else-statement associate with the first if-statement, curly braces must be used:

        int age = 17;
        if (age >= 18)
        {
          if (age <= 65)
            cout << "working age";
        }
        else
          cout << "not working age";

    Now the text “not working age” will be displayed, but only if age is under 18. If it’s over 65, no output is produced. The indentation is different above for readability, but the curly braces, indentation, are what changed the program behavior.

  • If-statements can also be nested to produce multi-way if-statements. For example:
        if(age < 13)
          cout << "child";
        else
          if(age < 18)
            cout << "teenager";
          else
            cout << "adult";

    One of the above outputs will always be produced. For better readability, however, the above code is usually written a bit differently:

        if(age < 13)
          cout << "child";
        else if(age < 18)
          cout << "teenager";
        else
          cout << "adult";

    The meaning of the code is exactly the same, but the indentation more clearly shows that one of the 3 options will always be executed.

  • moreInterest.cpp A version of the above interest program, with more if-statements, more interest rates.
  • In-class exercise: change the program from last class (ages.cpp above) to show who is younger or older as well.
  • agesThree.cpp: Solution to above in-class exercise

Logical Operators

  • && means logical AND. This “and sign” is usually called the “ampersand”. Two of them together mean logical intersection (both sides must be true).
  • || means logical OR. This vertical line is called the “pipe”. On the keyboard it usually has a break in the middle, and it’s the shifted back-slash (Shift + \). Two of them together mean logical union (either side must be true).
  • ! means logical NOT. This exclamation point means the opposite of what follows it (false becomes true and vice versa).
  • No strings of inequalities are allowed, e.g. Don’t write:
    1
    if (x &lt; y &lt; z)

    instead, write:

    1
    if (x &lt; y &amp;&amp; y &lt; z)

    Comparison operators are strictly binary, and they produce a boolean result.

  • You also cannot write something like:
    1
    if(age &gt;= 18 &amp;&amp; &lt;= 65)

    instead write:

    1
    if(age &gt;= 18 &amp;&amp; age &lt;= 65)

    Logical operators must work on boolean values.

  • Don’t use
    1
    !&lt;

    because it’s not valid. The way to write that is

    1
    &gt;=

  • Short-circuit evaluation- Sometimes, the result of an AND or OR expression can be determined without evaluating both sides of the AND or OR. This can save time, and it can also alter program behavior. For example:
        int num = 5, den = 0;
        if (den != 0 && num/den > 1)
          cout << " num is greater than den ";
        else
          cout << " den is 0 or it's greater than num";

    The above code will generate a run-time error (division by zero) if the right-side of the AND expression is evaluated. Fortunately, the left-side will evaluate to false, making the whole expression false no matter what the right expression produces. So the program will never perform the division, and no run-time error will result.

Boolean Expressions and Variables

  • Boolean – a term named after mathemetician George Boole, who formulated rules for mathematical logic. Refers to true/false values and logic corresponding to them.
  • bool – a datatype representing a boolean value. Can have literal values true or false.
  • Boolean expressions are most often used as the condition for a loop or if-statement. Such a condition is always evaluated for truth or falsehood, and if it’s true, the condition is satisfied.
  • You may store the result of a Boolean expression in a Boolean variable, and you may use that variable as the condition for an if-statement or loop. E.g.:
        int x = 5;
        bool b = x < 10;  // store true in b if x is less than 10, false otherwise
        if (b)   // means "if (b == true)"
          cout << "x is less than 10";  // this output will be displayed
  • The following program illustrates all of the above concepts: BooleanApp.cpp
  • In-class exercise: Modify the Names And Ages Program from the previous class exercise, so it outputs if one or both people are between 18 and 65 years old. You must use a logical and (&&) or or (||). Try using a bool variable as well. Here is some sample output:
        -bash-3.2$ a.out
        Please enter first person's name:
        Craig
        Please enter first person's age:
        37
        Please enter second person's name:
        Serafina
        Please enter second person's age:
        7
        Craig is between 18 and 65, but Serafina is not.
        -bash-3.2$ a.out
        Please enter first person's name:
        Tobias
        Please enter first person's age:
        5
        Please enter second person's name:
        Serafina
        Please enter second person's age:
        7
        Neither person is between 18 and 65.
        -bash-3.2$ a.out
        Please enter first person's name:
        Geoff
        Please enter first person's age:
        37
        Please enter second person's name:
        Craig
        Please enter second person's age:
        37
        Both people are between 18 and 65
        -bash-3.2$
  • NamesAndAgesPart3.cpp: Solution to above in-class exercise

Switch Statements

  • A switch statement is another alternative to a multi-way if-statement. It cannot express ranges of values such as (x < 0), but it is fast and clear when an expression is being checked for one of several possible values which are known at compile-time (a variable compared to one or more int or char literals or constants).
  • In addition, the switch statement can only be used with integer and character datatypes (int, char, byte, short, long).
  • Here is an example of a switch statement:
        switch(age)
        {
          case 16:                           // if age == 16
            cout << "you can now drive";
            break;
          case 18:                           // if age == 18
            cout << "you can now vote";
            break;
          case 21:                           // if age == 21
            cout << "you can now drink";
            break;
          default:           // if none of the above match age
            cout << "there is nothing special about your age";
        }
  • The default section is optional
  • The keyword break is needed to exit the switch statement. Without it, the next case’s code would be executed as well.
  • Example: SwitchGrades.cpp demonstrates switch statements

In-class exercise: write a program to input the user’s 5-digit ZIP code, and output which city they live in from the following table. Use a switch statement to do it.

 

First 3 digits of ZIP code City
900 or 901 Los Angeles (and area)
921 San Diego (and area)
937 Fresno (and area)
941 San Francisco
942 Sacramento
946 Oakland (and area)

SwitchZips.cpp: Solution to in-class exercise to determine city from ZIP code, using switch