Welcome to Lesson 8!

Learning Objectives
By the end of today's class, you should know...
  • How do you write a program where there are exactly two alternatives?
  • How do you format a program with an if clause and an else clause
  • How do you compare strings?

Announcements

  • Midterm 1 on Tuesday.
    • Study over your old quizzes, in-class activities and homework
    • Through today's lecture
  • Quiz 3 after the break

Review Activity

With a partner, answer the following questions:

  1. What does the following output to the console:

string info = "Dogs are the best!!";

cout << info.length() << " " << info.substr(1, 3) << " " << info.substr(14, 5) << endl;


  1. Find the mistake in the statements below. What will happen when the code is run?
int age;
cout << "Enter your age: ";
cin >> age;
if (age = 18) {
        cout << "First time voter!";
    }

Using if-else Statements

  • Sometimes we want to choose between two actions
  • If a condition is true
    • then do this
  • Otherwise it is false
    • so do something else
  • To make this type of selection we use an if...else statement
  • Syntax:
    if (test) {
       statements1
    } else {
       statements2
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementsX: the statements to execute depending on the test


C++ if...else statement

(from http://www.tutorialspoint.com/cplusplus/cpp_if_else_statement.htm)


  • For example:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • ****Note that there is no test condition for the else clause****
  • The decision on which set of statements to use depends on only one condition
  • Note that you could write an if-else as a pair of complementary if statements instead, like:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    }
    if (7 != guess) {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • However, it is easier and clearer to write an if-else statement instead
  • For clarity, write the if and else parts on different lines than the other statements
  • Also, indent the other statements
  • You can see an example of an if-else statement in the following example

Example Program With an if-else Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;


int main() {
    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;

    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    return 0;
}

Formatting the if Statement

  • It is important to format the if statement professionally
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • Note how the conditional code is indented inside both the if and else portions
  • This lets us easily see which code is conditional and which is not
  • Also note the placement of curly braces
  • Different groups have different practices for placing curly braces for placing curly braces of if and if-else statements
  • In practice, you should use the style dictated by your group's policy
    • Or your professor's instructions


Activity 8.1: Guessing Game (10 pts)

  • Find a partner for pair programming
  • Open CodeBlocks and create a new C++ file.
  • Add a block comment with your names and section information at the top.
  • Copy the code below into your file and save it as selection.cpp. Then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        int guess = 0;
        cout << "I'm thinking of a number between"
             << " 1 and 10.\nCan you guess it?\n\n"
             << "Enter your guess: ";
        cin >> guess;
        cout << "You entered: " << guess << endl;
    
        // Insert new statements here
    
        return 0;
    }
    
  • We want to let the user know if they entered a correct value. For this we need to add an if statement such as:
    if (7 == guess) {
        cout << "*** Correct! ***" << endl;
    }
    

    Statements inside the curly braces only execute if the test condition in the parenthesis, (7 == guess), evaluates to true. For more information, see section:

  • Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 7
    You entered: 7
    *** Correct! ***
    

    If you rerun the program and enter a number different than 7 (like 9) then the message saying correct will NOT appear.

  • For a friendlier game output, we should give a message when the user enters an incorrect value. For this we need to replace our if statement with an if-else statement like:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Please try again.\n";
    }
    

    Statements inside the curly braces of the else clause only execute if the test condition in the parenthesis, (7 == guess), evaluates to false. For more 

  • Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 9
    You entered: 9
    Sorry, that is not correct.
    Rerun and try again.
    

    The error message should appear for any number other than the correct guess.

  • One problem with our program is that a user may enter numbers outside the range of 1 through 10. We can test for this condition with one or more if statements. Add this code to your program after the input statement and before the other if statements:
    if (guess < 1) {
        cout << "Error: guess must be >= 1\n";
        return 1;
    }
    

    Checking user input is a common use of if statements. This type of code is known as input validation or input verification.

  • Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 0
    You entered: 0
    Error: guess must be >= 1
    

    The error message should appear for any number that is less than one.

  • Upload your activity to Catalyst when you are finished. Both partners need to submit for full credit.


Comparing Characters and Strings

  • Character data can be evaluated using relational operators as well
  • Comparing characters works because C++ stores characters as numbers using ASCII codes
  • Note that letters nearer to the start of the alphabet have lower numerical values
  • Thus a numerical comparison can decide the alphabetical order of characters

Example Program Comparing Characters

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

int main() {
    cout << boolalpha; // output true or false
    cout << "'A' < 'B': " << ('A' < 'B') << endl;
    cout << "'A' > 'B': " << ('A' > 'B') << endl;
    cout << "'A' <= 'Z': " << ('A' <= 'Z') << endl;
    cout << "'X' >= 'Y': " << ('X' >= 'Y') << endl;
    cout << "'X' == 'X': " << ('X' == 'X') << endl;
    cout << "'X' != 'X': " << ('X' != 'X') << endl;
}

Comparing Strings

  • We can compare strings using relational operators as well
  • C++ compares two strings using lexicographical order (a.k.a. alphabetic order)
  • For example, "car" is less than "cat":
    car
    cat
  • Also, "car" is less than "card"
    car
    card

Example Program Comparing Strings

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
using namespace std;

int main() {
    string s1, s2;
    cout << "Enter two strings: ";
    cin >> s1 >> s2;
    cout << boolalpha; // output true or false
    cout << s1 << " <= " << s2 << " : " << (s1 <= s2) << endl;
    cout << s1 << " > " << s2<< " : " << (s1 > s2) << endl;
}

Activity 8.2: Let's Alphabetize! (10 pts)

  • Open up CodeBlocks and create a new C++ file called alphabetize.cpp.
  • Our program will take in two string inputs from the user, compare then and the output the two strings in alphabetical order.
  • At the top of your program, declare a string variables called word1.
string word1;
  • Now declare a second string variable called word2.
  • Next, write a cout statement welcoming your user to the program and letting them know that this program will alphabetize two words.
cout << "Welcome! Give me two words and I will return them to you in alphabetical order!\n";
  • Run your program to make sure it is giving you the output you expected.
  • Let's prompt the user for the first word and store the result as word1.
cout << "Please enter the first word: ";
cin >> word1;

  • Do the same for the second word.
  • Now, let's create an if-else statement to determine the ordering of the two words. And, then output the result to our user. The if-else statement will need to use string comparison as discussed above.
  • The code that you have written could be a useful part of a larger program. 
  • Both partners should submit to Catalyst when finished.
Making Decisions Continued

"Nesting" if Statements
  • The inner if statement is evaluated only if the test condition of the outer if test first evaluates to true
  • The following code shows an example of a nested if statement

Example Showing a Nested if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main() {
    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;

    if (guess != 7) {
        if (guess < 7) {
            cout << "Your guess is too low.\n";
        } else {
            cout << "Your guess is too high.\n";
        }
    } else {
        cout << "*** Correct! ***\n";
    }

    return 0;
}

Nesting in the else Clause

  • You can also nest if statements in the else clause
  • When used this way, the computer can make only one selection
  • As soon as a condition is found to be true, the rest of the selections are ignored
  • The following code shows an example of a nested else if statement
  • For example:
    if (guess < 7)
    {
        cout << "Your guess is too low.\n";
    }
    else if (guess > 7)
    {
        cout << "Your guess is too high.\n";
    }
    else
    {
        cout << "*** Correct! ***\n";
    }
    
  • The trick in understanding this type of logic is to remember:
    • You start at the top
    • The computer makes only one selection
    • Once the selection is made and processes, the computer skips the rest of the options

Example Showing a Nested else if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main() {
    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;

    if (guess < 7) {
        cout << "Your guess is too low.\n";
    } else if (guess > 7) {
        cout << "Your guess is too high.\n";
    } else {
        cout << "*** Correct! ***\n";
    }

    return 0;
}

Programming Style: Indentation of if-else-if Statements

  • Note the alignment of the nested statements below:
    if (guess < 7)
    {
        cout << "Your guess is too low.\n";
    }
    else
    {
        if (guess > 7)
        {
            cout << "Your guess is too high.\n";
        }
        else
        {
            cout << "*** Correct! ***\n";
        }
    }
    
  • The above style is WRONG
  • Instead, we use:
    if (guess < 7)
    {
        cout << "Your guess is too low.\n";
    }
    else if (guess > 7)
    {
        cout << "Your guess is too high.\n";
    }
    else
    {
        cout << "*** Correct! ***\n";
    }
    
  • This shows more clearly that we are making a single choice among multiple alternatives
  • Also, it prevents indentations from cascading to the right as we add more selections

Multiple Alternatives

  • By using collections of if-else statements, a program can distinguish between multiple alternatives

Choosing Between Alternatives

  • This program has five alternatives to choose from:
    1. "penny"
    2. "nickel"
    3. "dime"
    4. "quarter"
    5. erroneous input
  • Note that the order that the alternatives are checked is unimportant
  • We can follow the alternatives in the flowchart shown below

Flowchart of Multiple Alternative for Converting Coins to Values


  • For example, consider the following example where a user enters the name of a coin, and the program displays the value:

    Program Converting Coin Names to Values

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Enter coin name: ";
        string name;
        cin >> name;
        double value = 0;
    
        if (name == "penny") {
            value = 0.01;
        } else if (name == "nickel") {
            value = 0.05;
        } else if (name == "dime") {
            value = 0.10;
        } else if (name == "quarter") {
          value = 0.25;
        } else {
            cout << name << " is not a valid coin name\n";
        }
        cout << "Value = " << value << "\n";
    
        return 0;
    }

Activity 8.3: Grades (10 pts)

We want to write a program to calculate a student's letter grade according to the following table:

Numerical GradeLetter Grade
greater than or equal to 90A
less than 90 but greater than or equal to 80B
less than 80 but greater than or equal to 70C
less than 70 but greater than or equal to 60D
less than 60F
  • Find a partner for pair programming.
  • Copy the following program into a text editor, save it as grader.cpp. Change the comments, then compile and run the starter program to make sure you copied it correctly.
/*
* Name 1
* Name 2
* Section
*/

#include <iostream> using namespace std; int main() { // Enter your code here return 0; }


  • Add code to get user input into a variable named score of type double. When you run the program after adding this code, the output should look like:
    Enter a score: 95.7
    

    Make sure you declare the variable with a compatible data type. Note that the underlined numbers above shows what theuser enters and is not part of your code

  • First we will look at a series of if statements and see that if statements alone are not enough to solve this problem. Copy the following into your program after the input statements:

    Compile and run your modified program. There is a logic problem with this code. Each test condition needs to work over a range of values rather than with a single value.

  • One way to correct the problem is to nest an if statement inside of another if statement. To see how this works, modify your code to add nested if statements as shown below:

    To test the range, the outer if statement tests the lower condition and the inner if statement tests the upper condition.

string grade;
if (score >= 90)
{
    grade = "A";
}
if (score >= 80)
{
    if (score < 90)
        grade = "B";
}
if (score >= 70)
{
    if (score < 80)
        grade = "C";
}
if (score >= 60)
{
    if (score < 70)
        grade = "D";
}
if (score < 60)
{
    grade = "F";
}
cout << grade << endl;
  • What is another way to fix this problem that we have already seen?
  • Perhaps the most elegant solution is to nest an if statement in the else clause of the preceding if. Modify the series of ifstatements to include an else clause as shown below:

          string grade;
    if (score > = 90)
    {
        grade = "A";
    }
    else if (score >= 80)
    {
        grade = "B";
    }
    //you fill in the statements here
    else
    {
        grade = "F";
    }
    cout << grade << endl;


  • We are nesting if statements in the else clause. Nesting in the else clause makes each test condition of the if statement exclusive of the others because each test condition eliminates all the preceding conditions.
  • Compile and run your modified program to make sure you made the changes correctly. When you run the program, the output should look like:
    Enter a score: 80
    B
    

    Run your program a few times with different score to verify that any score displays the correct letter grade.

  • When finished, upload your program to Catalyst.

Midterm Review

With a partner, correct the mistakes below


a.

string pet = dog;


if (pet = “cat”) {

    cout << “Meow!”;

} else (pet = “dog”) {

    cout << “Definitely not a cat!”;

}

b.

char = a;


With a partner, answer the following question:

  • What will the following print out to the console?

int num_puppies = 6;

if (num_puppies < 5) {

    cout << "Woof!" << endl;

} else {

    cout << "Bark!" << endl;

}

cout << "Arf!";




Wrap Up
  • Find a partner and answer the questions from today's learning objectives

Upcoming Assignments
  • Assignment 8 due Tuesday
  • Midterm 1 next class
  • Lab 5 due Friday at midnight