3. Branches

Review Topics


General Information

Housekeeping

  • Make sure you follow along with this page linked in Canvas
  • Please keep your microphone off unless you are asking a question
  • Please turn on camera if you can (optional)
  • Use chat if you would like to comment or ask questions

Announcements

See Announcements link in Canvas to keep up with what is going on. Here are a few for review:

  • ZyBook required for course--email me if this is a financial hardship
  • Remember that the exercises from this page are due Sunday at 9:00pm.
  • Grace period is over, but CAs, Labs, and Class Exercises may be completed up to two days late with a 10%/day penalty.
  • Free Fresh Market schedule: free fresh fruits and vegetables
  • Food & Housing Resources: free food, meals, temporary and permanent housing
  • COVID-19 Resources and Information: Includes loaner-laptop information
  • Campus WiFi Access

Homework Help

3.1: Readiness Assessment Quizzes

  • Reading and participation activities are due before the first class meeting of the week
  • Quizzes assess the comprehension of the reading and participation activities

Quiz Part 1: Individual Readiness Assessment

  • Complete this quiz solo to assess your reading comprehension and readiness
  • Must take this quiz before the class meeting to ensure you are ready for the team quiz
  • Quiz is open book and notes but timed
  • Highest score is counted so take the quiz multiple times

Quiz Part 2: Team Readiness Assessment (20m)

  • Must attend the class meeting to take this quiz
  • Login to Canvas
  • Will move to breakout rooms with your team
  • Make sure you have the access code for the exam
  • Openly discuss what you believe to be the best answers for the questions
  • Decide how to agree on the answers
    • Strive to reach a consensus on quiz answers
    • If no consensus, work it out as you and others in your group see fit
  • Turn in the quiz as a group
  • Each group member will receive the same score
  • Return to the main meeting room when finished

Quiz Appeals

  • After completing the team quiz, team members may appeal an answer
  • Appeals can be based on two criteria:
    1. Question is factually wrong

      Appeal must included citations to sources of information that document or support an alternative answer. Team may access reference materials during the appeal.

    2. Question is confusing based on it's wording

      Appeal must include an appropriate rewrite of questions or answers that you interpret as ambiguous or confusing.

  • Work with teammates to develop and write any appeals
  • Team has up to 24 hours after the quiz to email appeal to instructor
  • If appeal is granted, only the teams that submitted appeal gets credit

3.2: Pair Programming

Starting with week 3 lab projects, we will be using pair programming!

3.2.1: Introducing Pair Programming

  • Pair programming is a style of programming in which two people work together on one computer at the same time:
    • Exactly two people: not one nor three or more
    • Exactly one computer: not two or more
  • One person enters the code and the other reviews each line of code as it is entered
  • The person operating the mouse and keyboard is called the driver
  • The other person in the pair is called the navigator
  • The role of the navigator is to think about what needs to be done and where the project is going
  • The navigator duties may include:
    • Determining optimal algorithms
    • Analyzing the design and code to prevent errors

Why Pair Program?

  • Students who pair program report:
    • Higher confidence in a program solution
    • More satisfaction with programming
  • Instructors report higher completion and passing rates

Check Yourself

  1. True or false: pair programming typically results in fewer errors and programs take less time to complete.
  2. The job of the driver is to ________.
  3. The job of the navigator is to ________.
  4. To gain a different perspective on the problem being solved, after about 30 minutes change ________.
  5. True or false: in pair-programming, the person who owns the code is the person who wrote the code.

More Information

3.2.2: Best Practices

  • You may choose any other student in this class for a partner
    • You may NOT program with a person from outside the class
  • Both of your names appear on the assignment in the file comment block like
    /**
        CS-11 Lab 3.1: Enhanced calculator allowing selection of operator.
        @file calculator.cpp
        @author your name, partner's name
        @version 1.0 date completed
    */
    

    For full credit, make certain to type in real names and dates instead of the words your name, partner's name, and date completed.

  • When choosing partners and working together, certain practices help you perform better
  • Pair-programmers are usually more successful when they have similar experience levels
  • However, pair programming can work with partners of different experience levels
    • The more experienced partner must be ready to mentor rather than just develop the program
  • Find a partner with whom you can easily exchange ideas
  • If you cannot work easily with someone, get another partner
  • The Rules of Pair Programming

If you have not completed the Module 2 Pair Programming page and quiz, make sure you do so right away.

Check Yourself

  1. True or false: there are no rules in pair programming.
  2. True or false: the rules of pair-programming require you to use only one computer at a time to edit and compile code.
  3. One way to pair program using Zoom is to share your ________.

More Information

Exercise 3.2: Finding a Partner (12m)

In this exercise we see who might be a compatible pair-programming partner for the next lab projects.

Remember that you may change pair programming partners from week to week.

Specifications

  1. We will divide into breakout rooms.
  2. Within your team, exchange names and email addresses, or other contact information, and then write down everyone's information.
  3. Next to each name, write the amount of programming knowledge and experience for that student using the following scale:
    1. Absolute beginner
    2. Some coding knowledge like HTML or calculator programming
    3. Can program satisfactorily in another programming language
    4. Can program satisfactorily in C++
  4. Save all the information you collect in a file named students.txt.

    Note that you can choose to have one person in your group record the information and email it to all the students in the group. However, every student must submit the same list of students.

  5. Save the students.txt file so you can submit it to Canvas as part of Week 3 Exercises.

3.3: Equality and relational operators

  • C++ allows a program to test a relationship between two values
  • A relational operator compares two operands like:

    relational expression

  • The above example is called a relational expression
  • A relational expression uses a relational operator to compare two entities like numbers or variables
  • We have used relational operators in algebra and relational operators in C++ are similar
  • In algebra these operators tend to be called equalities (like 5 = 5) and inequalities (like 4 ≥ 3).
  • The following table shows the similarities and differences between algebra and C++

3.3.1: Table of equality and relational operators

Math Name C++ Examples   Result Notes
= Equal to == 5 == 10
2 == 2
false
true
Do not confuse with = which is assignment.
Not equal to != 5 != 10
2 != 2
true
false
The ! is like the line that "crosses through" the equal sign.
< Less than < 5 < 10
5 < 5
5 < 2
true
false
false
Less than or equal to <= 5 <= 10
5 <= 5
5 <= 2
true
true
false
Be careful not to write =<. Code the symbols in the order people normally say them.
> Greater than > 5 > 10
5 > 5
5 > 2
false
false
true
Greater than or equal to >= 5 >= 10
5 >= 5
5 >= 2
false
true
true
Be careful not to write =>. Code the symbols in the order people normally say them.

Check Yourself

  1. What is the value of the following test conditions, given x = 3, y = 7?
    1. (x != y)
    2. (x == y)
    3. (x < y)
    4. (x >= y)
  2. The problem with the following test condition is ________.
    if (x =< 42)
    
  3. The value of x after the following code executes is ________.
    int x = 3;
    int y = 4;
    if (x < y)
    {
      x = y;
    }
    
  4. The value of y after the following code executes is ________.
    int x = 42;
    bool y = (x == 3);
    

3.3.2: Boolean Variables and Relationships

  • Notice that relational expressions always evaluate to either true or false
  • To store a condition that can only be true or false, we use a Boolean variable
  • Boolean variables are named after George Boole (1815-1864), a pioneer in the study of logic
  • We specify a Boolean variable using the bool type, which can hold just one of two values: true or false
    bool isCool = true;
    bool lies = false;
    
  • Thus we can assign a relational expression to a Boolean variable
    bool test = 5 != 2;
    cout << boolalpha; // show true or false
    cout << test << endl;
    

Exercise 3.3: Test Condition Activity (2m)

Formulate the following test conditions in C++, then check your answer by pressing the answer link. Press Submit Work when correct.

answer
answer
answer
answer
answer
answer

3.4: Making Decisions

  • Flow of control (or control flow) refers to the order in which programs execute instructions
  • By default, code executes sequentially: one statement after another from top to bottom in a function like main()
  • Sometimes we want to change this sequential flow
  • One change we can make is a using a branch, also known as a selection statement or conditional statement
  • A branch contains code that executes statements only if a test condition evaluates to true
  • One way to create the test condition is with equality and relational operators

3.4.1: Making Decisions with if-Statements

  • An if-statement contains code that executes statements only if a test condition evaluates to true
  • For example:
    if (7 == guess)
    {
        cout << "*** Correct! ***" << endl;
    }
    
  • In the above, the (7 == guess) is a test that the 7 is equal to the value of guess
  • Remember that the == is the equality operator

Bill Gates explains If statements

Syntax of an if-statement

  • An if statement has two parts: a test and a body
  • The body can have zero or more statements
  • The statements in the body execute if and only if the test evaluates to true
  • If the test condition evaluates to false, the computer skips the code
  • Syntax:
    if (test)
    {
       statement1
       statement2
       ...
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementX: the statements to execute depending on the test
  • See how our example matches the syntax:
    if (7 == guess)
    {
      cout << "*** Correct! ***\n";
    }
    
  • For clarity:
    • Write the if on a different line than the body
    • Indent within the curly braces

Diagram of if Statement Operation

If statement operation

Example Program With an if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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! ***" << endl;
    }
    return 0;
}

About those Curly Braces

  • Technically, the if statement affects only the single statement that follows
  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the body
  • Curly braces are not always required, but the best practice is to always include them

More Information

Check Yourself

  1. True or false: the default behavior for a computer program is to execute statements sequentially.
  2. To execute statements only when a certain condition is true, use an ______ statement.
  3. True or false: an if-statement requires a test condition.
  4. Of the following, ________ would be valid as the first line of an if-statement?
    1. if (guess = 7)
    2. (guess if 7)
    3. if (7 == guess)
    4. (7 if guessed)
  5. The code inside the curly braces executes when x is equal to ________.
    if (x == 3)
    {
      x = 1;
    }
    
  6. The value of x after the following code executes is ________.
    int x = 7;
    if (x == 3)
    {
      x = 1;
    }
    
  7. True or false: an if-statement affects only the single statement following it unless curly braces are used.

3.4.2: Comparing Characters

  • Character data can be compared using equality and relational operators
  • Relational operators are useful for making alphabetic comparison between characters, like:
    if ('A' < 'B')
    
  • Since C++ stores characters as numbers using ASCII codes, the computer is actually comparing numbers
    if (65 < 66)
    
  • Letters nearer to the start of the alphabet have lower numerical values than later letters
  • Thus a numerical comparison can decide the alphabetical order of characters
  • Remember that relational expressions always evaluate to the equivalent of true or false

Example Program Comparing Characters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;

int main() {
    char chOne, chTwo;
    cout << "Enter two characters separated by whitespace: ";
    cin >> chOne >> chTwo;
    string quote = "'"; // string variable for quote
    string ch1 = quote + chOne + quote; // first char as string
    string ch2 = quote + chTwo + quote; // second char as string

    if (chOne == chTwo) {
        cout << ch1 + " == " + ch2 << endl;
    }
    if (chOne != chTwo) {
        cout << ch1 + " != " + ch2 << endl;
    }
    if (chOne < chTwo) {
        cout << ch1 + " < " + ch2 << endl;
    }
    if (chOne <= chTwo) {
        cout << ch1 + " <= " + ch2 << endl;
    }
    if (chOne > chTwo) {
        cout << ch1 + " > " + ch2 << endl;
    }
    if (chOne >= chTwo) {
        cout << ch1 + " >= " + ch2 << endl;
    }
}

Check Yourself

  1. What is the result of evaluating the following relational expression? (answer)
    'A' < 'B'

More Information

3.4.3: 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
  • For example:
    if (7 == guess)
    {
        cout << "*** Correct! ***\n";
    }
    else
    {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    

Diagram of if-else Statement Operation

If else operation

  • Notice that there is no test condition for the else clause
    if (7 == guess)
    {
        cout << "*** Correct! ***\n";
    }
    else
    {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • The decision on which set of statements to use depends on only one condition
  • As an option we 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
  • For clarity, write the if and else parts on different lines than the other statements
  • Also, indent the other statements
  • Here is an example of an if-else statement

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-else 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
  • As an alternative we could format the if-else as follows:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • 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
  • For the acceptable styles for this course see my instructions on: Curly Braces

Check Yourself

  1. True or false: an if-else statement allows the programmer to select between two alternatives.
  2. What is wrong with the following if-else statement? (answer)
    if (7 == guess) {
        msg = "*** Correct! ***";
    } else (7 != guess) {
        msg = "Sorry, that is not correct.";
    }
    
  3. What is the value of x after the following code segment? (answer)
    int x = 5;
    if (x > 3) {
        x = x - 2;
    } else {
        x = x + 2;
    }
    
  4. True or false: always indent inside the curly braces of an if-else-statement.

Exercise 3.4: Guessing Game (10m)

In this exercise we explore the use of relational operators with if statements to create a simple game.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it, update the code in the text editor, and then compile and run the starter program to make sure you updated 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;
    
  2. We want to let the user know if they entered a correct value. For this we need to add an if statement where indicated in the code:
    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.

  3. 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.

  4. For a friendlier game output, we should give a message when the user enters an incorrect value. For this we 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 << "Rerun and 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 information, see textbook section on If-else.

  5. 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.

  6. 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; // Exits program
    }
    

    Checking user input is a common use of if statements.

  7. 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.

  8. Once satisfied with your code, copy your code into a text editor, save the file as "guess.cpp", and to submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

3.5: Multiple Alternatives

  • By using nested if-else statements, a program can distinguish between multiple alternatives
  • One way is to nest in the if clause
  • Another way to nest if statements in the else clause

3.5.1: Nested if Statements

  • We can nest if statements within other if statements
  • The inner if statement is evaluated only if the test condition of the outer if test first evaluates to true
    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";
    }
    
  • Nesting allows us to test to test multiple conditions and select from multiple alternatives
  • We can nest if-statements in either the if-clause or the else-clause
  • When nested in the else-clause, a program makes only one selection among all the alternatives
  • As soon as a condition evaluates to true, the rest of the selections are ignored
  • Because of these properties, if-else-if statements are usually formatted as follows:
    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 formatting more clearly shows the sequence of tests, which are:
    • The computer starts at the top
    • The computer makes only one selection
    • Once the selection is made and processes, the computer skips the rest of the options
  • The formatting also prevents indentations creeping to the right as more selects are added

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 style 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
  • Optionally, we may put the opening curly brace on the same line as the test condition
    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";
    }
    

Check Yourself

  1. True or false: you can nest if statements in the if clause, the else clause, or both.
  2. In the following code snippet, the if (guess < 7) is nested in the ________
    1. the outer if-statement
    2. the outer else clause
    3. the inner if-statement
    4. the inner else clause
    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";
    }
    
  3. In the following code snippet, the if (guess > 7) is nested in the ________
    1. the outer if-statement
    2. the outer else clause
    3. the inner if-statement
    4. the inner else clause
    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";
    }
    
  4. True or false: in the above sequence of if-else statements, the final else clause belongs to the first if-statement.
  5. True or false: if you have a series of test conditions, and only one can be correct, the following is a good style for your code's structure.
    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";
    }
    

Exercise 3.5: Multiple Alternatives (15m)

In this exercise we test multiple alternatives in a program. As an example, we will calculate a student's letter grade according to the following table.

Grading Scale
Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F

Remember to verify your code by compiling after each step.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        double score;
        cout << "Enter a score: ";
        cin >> score;
        // Enter your code here
    
        return 0;
    }
    
  2. Compile and run the starter program to make sure you entered it correctly.

    When you run the program, the output should look like this:

    Enter a score: 42
    

    Where 42 is the number entered by the user, shown in aqua italics for emphasis.

  3. Add the series of if statements shown below into your code:
    if (score >= 90) {
        cout << "A\n";
    } else if (score >= 80) {
        cout << "B\n";
    } else if (score >= 70) {
        cout << "C\n";
    } else if (score >= 60) {
        cout << "D\n";
    } else {
        cout << "F\n";
    }
    

    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. Thus, in this scenario the order is important.

  4. 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 scores to verify that any score displays the correct letter grade.

  5. Once satisfied with your code, copy your code into a text editor, save the file as "grader.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

3.6: Logical Operators

  • Sometimes we need to test for multiple conditions in our programs
  • For example, we want to test for membership and an age >= 21
  • We need to test both for membership and age >= 21
  • One way to make the tests is with nested if-statements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main() {
    cout << "Are you a member? (y/n): ";
    char member = 0;
    cin >> member;

    cout << "Enter your age: ";
    int age = 0;
    cin >> age;
    if (member == 'y') {
        if (age >= 21) {
            cout << "You may enter!\n";
        } else {
            cout << "Entry denied.\n";
        }
    } else {
        cout << "Entry denied.\n";
    }

    return 0;
}
  • If both the membership and age is correct, we get the message, "You may enter!"
  • If either the membership or age entered is not correct, we get the message, "Entry denied."
  • While this approach works, it is cumbersome to code and read
  • A better approach is to combine test conditions with logical operators

Combining Test Conditions with Logical Operators

  • A logical operator, or Boolean operator, is a connective for Boolean values (true or false)
  • C++ has several logical operators, but we only need to use three to create any possible test condition
  • These three key operators are and, or and not, which are discussed below
  • These logical operators are traditionally written as && (and), || (or) and ! (not)
  • Both variants are legal under ANSI C++
  • The words are easier to read but many C++ programmers still use the older form

Truth Tables for and, or and not

and (&&) Operator Truth Table
If expr1 is... And expr2 is... Then expr1 and expr2 is... Example Result
true true true 5 < 10 and 5 > 2 true
true false false 5 < 10 and 5 < 2 false
false true false 5 > 10 and 5 > 2 false
false false false 5 > 10 and 5 < 2 false
or (||) Operator Truth Table
If expr1 is... || expr2 is... Then expr1 or expr2 is... Example Result
true true true 5 < 10 or 5 > 2 true
true false true 5 < 10 or 5 < 2 true
false true true 5 > 10 or 5 > 2 true
false false false 5 > 10 or 5 < 2 false
not (!) Operator Truth Table
If expr is... Then ! expr is... Example Result
true false !true false
false true !(5 < 2) true

Example Using Logical Operators

  • We could rewrite our membership and age test using an and (&&) operator like this:
    if (member == 'y' and age >= 21)
    {
        cout << "You may enter!\n";
    }
    else
    {
        cout << "Entry denied.\n";
    }
    
  • Notice that the code is shorter and it is easier to follow the with nested if-statements
  • Another way to use logical operators to test the membership and age is:
    if (member != 'y' or age < 21) {
    {
        cout << "Entry denied.\n";
    }
    else
    {
        cout << "You may enter!\n";
    }
    
  • Many people confuse && and || conditions, especially when learning about logical operators
  • A value lies between 0 and 100 if the value is at least 0 and at most 100
  • A value is outside that range if it is less than 0 or greater than 100
  • There is no golden rule; we have to think carefully and test our conditions

Another Look at Truth Tables

  • Note that most computers store true as 1 and false as 0
  • If we substitute 1 for true and 0 for false, we have these truth tables:

two value logic tables

  • With this substitution we see that the AND operation is the minimum of the operands
  • Conversely, the OR operation is the maximum of the operands
  • The NOT operator simply reverses its operand

Parenthesis

  • Remember that a Boolean expression in an if statement must be enclosed in parenthesis
  • Thus, an if statement with && might look like:
    if ((guess != GUESS1) && (guess != GUESS2))
  • However, relational operators have a higher precedence than logical operators
  • Thus, we can remove the inner parenthesis without affecting the meaning:
    if (guess != GUESS1 && guess != GUESS2)
  • In coding, clarity is more important than brevity
  • Thus, if using parenthesis is easier to understand then use the extra parenthesis

Example Program with Logical Operators

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

int main()
{
    cout << "Enter two operands using 1 for true and 0 for false: ";
    bool op1 = false, op2 = false;
    cin >> op1 >> op2;
    cout << op1 << " and " << op2 << " = " << (op1 and op2) << endl;
    cout << op1 << " or " << op2 << " = " << (op1 or op2) << endl;
    cout << "Not " << op1 << " = " << (!op1) << endl;
    cout << "Not " << op2 << " = " << (!op2) << endl;

    return 0;
}

More Information

Check Yourself

  1. Of the following groups ________ is larger.
    1. Students wearing denim
    2. Students wearing denim AND corrective lenses
  2. Of the following groups ________ is larger.
    1. Students wearing denim
    2. Students wearing denim OR corrective lenses
  3. Of the following groups ________ is larger.
    1. Students wearing denim
    2. Students wearing denim AND NOT corrective lenses
  4. For the following code, the test condition evaluates to ________.
    bool denim = true;
    bool lenses = false;
    cout << (denim && lenses)
    
  5. For the following code, the test condition evaluates to ________.
    int age = 21;
    cout << (age >= 18 && age <= 25)
    
  6. Of the following logical expressions, the test to see if x is between 1 and 10 (including 1 and 10) is ________.
    1. (x >= 1 && x <= 10)
    2. (1 <= x and x <= 10)
    3. (x >= 1 || x <= 10)
    4. (1 <= x or x <= 10)

Exercise 3.6: Programming Logical Operators and Booleans (15m)

In this exercise we test multiple alternatives in a program using logical operators and the bool data type. As an example, we will calculate a simple guide of what to eat when you are hungry depending on the temperature.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

As you work through the exercise, I suggest that you compile after each step so you know where an error is located if you make a mistake. Also, if you get stuck then ask a teammate or the instructor for help.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Enter the temperature in degrees fahrenheit: ";
        int temp = 0;
        cin >> temp;
        cout << "Are you hungry? (y/n): ";
        char answer = 'n';
        cin >> answer;
        // Enter your code here
    
        return 0;
    }
    
  2. Compile and run the starter program to make sure you entered it correctly.

    When you run the program, the output should look like this:

    Enter the temperature in degrees fahrenheit: 100
    Are you hungry (y/n): y
    

    Where the input is shown in aqua italics for emphasis.

  3. After the user enters whether or not the person is hungry, convert the answer to a boolean variable named hungry using a relational expression like:
    bool hungry = (answer == 'y');
    
  4. Add the series of if statements shown below after the previously entered code:
    if (hungry && temp >= 100) {
        cout << "Eat ice cream\n";
    } else if (hungry && temp <= 0) {
        cout << "Eat spicy food\n";
    } else if (!hungry) {
        cout << "Do not eat anything\n";
    } else {
        cout << "Eat favorite food\n";
    }
    
  5. Compile and run your program to make sure you made the changes correctly. When you run the program, the output should look like:
    Enter the temperature in degrees fahrenheit: 100
    Are you hungry? y
    Eat ice cream
    

    Run your program a few times with different inputs to verify the choices make sense.

  6. Once satisfied with your code, copy your code into a text editor, save the file as "foodguide.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

3.7: Floating-point comparisons

  • Floating-point numbers should not be compared using ==
  • The reason is that some floating-point numbers cannot be represented exactly
  • For example (Repl.it):
    #include <iostream>
    #include <iomanip> // Zybook 2.7
    using namespace std;
    
    int main() {
        cout << fixed << setprecision(20);
        cout << 4.35 << endl;
        return 0;
    }
    
  • Memory is limited in floating point numbers to 64 bits
  • However, floating point numbers expected to be equal may be close enough
  • For example:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main() {
        cout << fixed << setprecision(20);
        double test = 1.0 - 0.9 - 0.1;
        cout << test << endl;
        if (test == 0.0) {
            cout << "Equal" << endl;
        } else {
            cout << "Not equal" << endl;
        }
        return 0;
    }
    
  • A better approach is to test if the value is close enough
    #include <iostream>
    #include <iomanip>
    #include <cmath>
    using namespace std;
    
    int main() {
        cout << fixed << setprecision(20);
        double test = 1.0 - 0.9 - 0.1;
        cout << test << endl;
        if (fabs(test - 0.0) < 0.001) {
            cout << "Close enough!" << endl;
        } else {
            cout << "Not close" << endl;
        }
        return 0;
    }
    

Exercise 3.7: Close Enough or Not (10m)

In this exercise we explore how to compare floating point numbers.

To develop the code, we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    #include <cmath>
    #include <iomanip>
    using namespace std;
    
    int main() {
        double firstNum = 0;
        double secondNum = 0;
        double diff = 0;
    
        cout << setprecision(30); // number of decimal places to show
        cout << "Enter the first number: ";
        cin >> firstNum;
        cout << "You entered this number: " << firstNum << endl;
        cout << "Enter the second number: ";
        cin >> secondNum;
        cout << "You entered this number: " << secondNum << endl;
        cout << "Enter the acceptable difference: ";
        cin >> diff;
    
        // Insert new statements here
    
        return 0;
    }
    
  2. Compile and run the starter program to make sure you entered it correctly.

    When you run the program, the output should look like this:

    Enter the first number: 4.35
    You entered this number: 4.34999999999999964472863211995
    Enter the second number: 4.34
    You entered this number: 4.33999999999999985789145284798
    Enter the acceptable difference: .01
    

    Where the input is shown in aqua italics for emphasis.

  3. We want to let the user know if the two numbers are close enough or not. For this we need to add an if-else statement where indicated in the starter code:
    if (fabs(firstNum - secondNum) < diff) {
        cout << "Close enough!" << endl;
    } else {
        cout << "Not close." << endl;
    }
    

    Notice that we compare the absolute difference of the two numbers.

  4. Compile and run your program again and verify the output looks like:
    Enter the first number: 4.35
    You entered this number: 4.34999999999999964472863211995
    Enter the second number: 4.34
    You entered this number: 4.33999999999999985789145284798
    Enter the acceptable difference: .01
    Close enough.
    

    Where the input is shown in aqua italics for emphasis.

  5. Try changing the acceptable difference and find a value that is not close enough.
    Not close.
    
  6. Once satisfied with your code, copy your code into a text editor, save the file as "fpcompare.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

Last Updated: February 11 2021 @23:01:44