3: Strings and Selection

What We Will Cover


Continuations

Questions from last class or reading?

Homework Questions?

  • A2-Math and Memory (2/8/17)
  • What was the hardest part of writing the code?
  • How useful was the example run for determining how the program operated?
  • How did you keep the line length to 80 characters or less?
  • What was the most informative CodeLab exercise?

Compiling and Running a Program Using TextPad

  • Many text editors have provision for compiling within the editor
  • We use TextPad in our class room as a text editor
  • Note that you can install TextPad at home

    See HowTo'sHow To Setup TextPad for Writing C++ Programs

  • To make your in-class exercises easier, we have set up TextPad to compile and run C++ programs
  • We will use the following program for demonstration
1
2
3
4
5
6
7
#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!\n";
    return 0;
}

Compiling with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Compile C++
  4. If there are any syntax errors, you will see a page or area showing them
  5. Otherwise, you will return to your source code page

Running Programs with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Run C++ Application
  4. Your program will run in a console window

3.1: Variables Revisited

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create variable names according to the rules of C++
  • Write code for declaring variables and assigning them values
  • Trace variable assignment operations

3.1.1: Review of Variables

  • Memory is important in a computer program, just like in real life
  • We can do very little without memory in computer programs (or real life)
  • To remember something in C++, we use a variable
  • variable: the name of a place to store data in a computer's memory

Variable Declaration

  • The following statement declares a variable:
    int x;
    
  • When we declare a variable we tell the computer to set aside space to store data in its memory
  • Notice that a variable declaration has two parts:
    dataType variableName;
  • Where:
    • dataType: the type of data the variable will store
    • variableName: the name of the variables
  • In our example
    int x;
    
    • int: the data type telling the computer to store integer values
    • x: a name we made up for the variable

Storing a Value

  • After declaring a variable, we give it a value with an assignment statement
    x = 42;
    
  • The equals (=) sign is how we make an assignment statement
  • An assignment statement sets or resets the value stored in a variable
  • The variable in which to store the data is always on the left-hand side of the equals (=) sign
  • The value to assign is on the right-hand side of the equals (=) sign
  • Notice that we can both declare a variable and assign it a value in one statement:
    int x = 42; // declaration + assignment
    
  • Good programming practice says we should assign a value when we declare a variable

Check Yourself

  1. The name of a location to store data in a computer's memory is known as a(n) ________.
  2. True or false: remembering data is rarely important when processing information.
  3. To specify the type of data stored in a variable, variable declarations include a(n) ________ ________.

3.1.2: Variable Names

  • A variable name is a sequence of letters, digits, underscores ( _ ) and currency symbols like a $
  • However, the name must start with either a letter, underscore character ("_") or currency symbol
    • Cannot start with a number
    • A currency symbol is allowed but its use is discouraged
  • Also, a variable name cannot be one of the C++ reserved words (keywords)
    • For a list of reserved words, see: C/C++ Keywords
    • Keywords have a predefined meaning in the C++ language
  • Note that we cannot have spaces in a variable name
    • A space is NOT a letter, digit, underscore character or currency symbol
  • Also, variable names are cAsE sEnSiTiVe
    • id, ID, iD and Id are all valid but different names

Programming Style: Variable Naming Conventions

  • Use meaningful names that are easy to remember
    • Well-chosen identifiers make it easier for other programmers (like the instructor) to understand your program
    • For example, the following is syntactically correct:
      a = b * c;
    • However, it hides the intent or meaning
    • Contrast this with:
      weeklyPay = hoursWorked * payRate;
    • This tells other programmers the intent and meaning of the code
  • Use a consistent naming style, one of the following two commonly-used styles:
    1. Start with a lower-case letter and use uppercase letters as separators. Do not use underbars ('_').
      int myVar
    2. Use all lower case letters and use underbars ('_') as separators.
      int my_var
  • We must be consistent and only use one style in a program.
  • The instructor's preference is the first style.

Group Activity

Which of the following are valid variable names?

  1. int myHello2;
  2. int 2myHello;
  3. int My_HeLlO;
  4. int my hello;
  5. int _a_very_long_variable_name_that_is_hard_to_read;
  6. int hel-lo;

Check Yourself

  1. True or false: a variable is how a program stores data in a computer's main memory.
  2. True or false: a data type like int tells a computer program the kind of data we want to work with.
  3. Write the code to declare an int variable named foo and assign it a value of 10.

    answer

3.1.3: More About Data Types

  • Like human memory, a computer must encode information before storage
  • The data type tells the computer how to encode the data and how much memory space to set aside

    Data type: a set of values from which a variable may take its value

  • C++ requires that every variable has a data type
  • The compiler verifies that a type is declared for a variable
  • There are several primitive built-in types in C++:
Category Typical
Keyword
Explanation
Boolean bool Logical values true or false
Character char Single letters, digits and special symbols like 'A' and '9'
Integer int Numbers without decimal points like 123, -987
Floating-point double Numbers with decimal points like 1.23, -0.01
  • In addition, there are user defined types we will discuss later in the course
  • To specify a basic data type, we use a keyword that specifies the type
  • The most commonly used basic C++ data types we use in this course are:
Type Typical
Bytes
Use
bool 1 A true or false value.
char 1 All ASCII characters.
int 4 Integers with a range from -2,147,483,648 to 2,147,483,647.
unsigned int 4 Integers with a range from 0 to 4,294,967,295.
float 4 Single-precision, floating-point numbers with 6 or 7 significant digits, +/- range, and exponents from about 10-45 to 1038.
double 8 Double-precision, floating-point numbers with 14 to 15 significant digits, +/- range, and exponents from 10-323 to 10308.
  • Note that the number of bytes used for storage depends on the system and compiler

Examples of Variables with Data Types

bool isCool;
char letterGrade;
int numStudents;
unsigned degreesKelvin;
float aBoat;
double pi;

Enforcing Data Types

  • The compiler verifies that a type is declared for a variable
  • Each variable can only store one type of data

    Data type: a set of values from which a variable may take its value

  • A data type is important because it tells the compiler how the programmer intends to use the data
  • For instance, we want some variables to store numbers and others to store text
  • We can think of a data type as a child's game where we match shapes to holes

Matching shapes to holes

When to use Integer and Floating-Point Numbers

  • Floating point values include whole numbers like:
    0.0   1.0   -1.0  2000000000.0
    
  • If floating point values include whole numbers, why use integers?
  • Here are three good reasons NOT to use floating-point numbers
    1. Floating point values are not continuous and have gaps in the numbers they support
    2. Floating point values may incur rounding errors in some calculations
    3. Floating point values require more work for the computer to perform
  • Thus we should always use integer values whenever possible
  • Only use floating-point numbers when necessary

Group Activity: Name that Data Type!

Literal Data Type
'A'
-213.555
42
42.0
true
'Z'
false

Solo Activity (3m)

On a piece of paper write a variable declaration for:

  1. A variable to store dollars and cents
  2. A variable to store the count of the number of people in a room
  3. A variable to store a single letter
  4. A variable to store whether or not a light bulb is on or off

Have your deskmate verify your variable declarations and write their name on your paper as having verified your work.

More Information

3.1.4: Variable Assignment

  • After declaring a variable, we give it a value with an assignment statement like:
    x = 42;
    
  • To assign values, we use an assignment operator which is the "equals sign" (=)
  • An assignment statement sets or resets the value stored in a variable
  • The assignment is made in an assignment statement in this form:
    variable = expression;
  • Where:
    • variable: the name of the variable
    • expression: the data we want to store in the variable
  • An assignment statement assigns the value of expression (right side) to the variable (left side)
  • The simplest expression is a literal value:
    length = 25;
    width = 17.5;
    
  • Numbers like 25 and 17.5 are called literals because they represent exactly what they are literally
  • In each statement above, the value on right is assigned to the variable on the left
  • We may assign results of more complex expressions to a variable like:
    total = num1 + num2;
    slope = (y2 - y1) / (x2 - x1);
    
  • The expression on the right is evaluated (computed) before assignment to the variable on the left
  • Assignment causes the value in a variable to change

Assigning Initial Values to Variables

  • Initial values may or may not be assigned when variables are declared:
    // Not initialized when declared and have unknown values
    int sum;
    double amount;
    
    // Initialized when declared with assigned values
    int sum = 0;
    double amount = 42 * 2;
    
  • Good programming practice: initialize variables when declared

Variable Assignment Flow

  • A computer is a machine with a memory that follows a set of instructions
  • For a computer, or anyone, to follow a set of instructions it must know two things
    1. the actions to be taken
    2. the order of the actions
  • A computer always follows a set of instructions in order from first to last
  • When working with variables, we must keeps this property of computers in mind
  • First, a variable must be declared
  • Next a variable must be assigned a value with an assignment statement
  • To change the value of a variable we can reassign a value with another assignment statement
  • The original value is overwritten and replaced by the new value
  • The equals (=) sign does not express equality as it does in math

Solo Activity (2m)

On your paper from the last activity, write a statement to assign a value to each variable you declared.

Check Yourself

  1. True or false: the "equals sign" (=) is the assignment operator in C++.
  2. True or false: in an assignment statement, the value on the left is assigned to the variable on the right.
  3. After executing the following statement, the value of number is ________.
    int number;

Exercise 3.1: Variable Assignment Tracing (16m)

Understanding variables and assignment is critical to being able to program but is an easy thing to be confused about. Get over this hurdle and programming will be far easier.

In this exercise we complete a series of dry run exercises where we step through short fragments of code. This is an important activity to reinforce your understanding of variables. The instructor will step through the first exercise with you.

Specifications

  1. Use your paper from the last Solo Activity to record your answers, making sure to put the exercise name and your name on the paper.
  2. Open the Variable Assignment Tracing Exercises page.
  3. Click the first problem and follow the steps, filling in the boxes to get the final answers.
  4. After completing a problem and before continuing to the next, compare your answers with another student.
  5. If there is a disagreement, ask the instructor for clarification.
  6. After verifying your answer, record the problem number and final values of all variables on your paper.
  7. Repeat for the remaining exercise problems.
  8. After finishing all the exercise problems, answer the Check Understanding questions and record the question number and answer on your paper.

When finished, please help those around you.

3.1.5: Summary

  • Variables are how we can store data in our programs
  • Variables must be declared before use like:
    int x;
    
  • One declared we can assign a value to the variable like:
    x = 42;
    
  • Simple assignment statements have a variable, equals sign and an expression:
    variable = expression;
  • The right-hand side expression is computed before the assignment
  • Thus assignment work by copying from the right-hand side of the equals sign to left-hand side
  • The variable must always be on the left-hand side of the assignment statement
  • Variables can be assigned new values while our program executes
  • When assigning values, programs execute in order from top to bottom
  • Variables can only hold one value at a time
  • Thus old values disappear when a variable is assigned a new value
  • Values placed into a variable replace (overwrite) previous values:

    Assigning a value to a variable

Self Reflection

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

  1. How do you store information in a computer's main memory? (3.1.1)
  2. What code would you write to declare an int variable named foo and assign it a value of 10? (3.1.1)
  3. Which of the following are valid variable names? (3.1.2)
    1. int myHello2;
    2. int 2myHello;
    3. int My_HeLlO;
    4. int my hello;
    5. int _a_very_long_variable_name_that_is_hard_to_read;
    6. int hel-lo;
  4. What is the purpose of a data type like int or double? (3.1.3)
  5. What data values can you store in each of the following data types? (3.1.3)
    1. bool
    2. char
    3. int
    4. double
  6. Which symbol is the assignment operator? (3.1.4)
  7. What does the assignment operation do? (3.1.4)

3.2: Characters and Strings

Learner Outcomes

At the end of the lesson the student will be able to:

  • Identify characters and strings from their literal representation
  • Assign characters and strings to variables
  • Concatenate strings
  • Collect characters and strings from user input
  • Output characters and strings

3.2.1: Type char

  • In addition to numbers, computers can manipulate text and other non-numerical types
  • Values of type char (short for character) are a single letter, number or special symbol
  • We specify a character by enclosing it in single quotes (")
    • The quote marks are not part of the data
  • For example:
    'a'   'b'   'Z'   '3'   'q'   '$'   '*'

ASCII Code

  • When we use a char data type, we store the character using an ASCII code
  • ASCII is a coding method that assigns a number to every character
  • Remember that computers store only numbers
  • So to handle text, each character is assigned a number as shown below
  • Each character requires 7-bits, which means it fits within one byte
  • ASCII was the first standardized code but is limited to English
  • However, ASCII has been extended to include all languages
  • The extended ASCII code is called Unicode

Table of ASCII Codes

ASCII table

Source: imageKB.com

Declaring and Assigning char Variables

  • As with other data types, we must declare char variables before use:
    char letterA;
  • We assign values to a char variable using the equals sign:
    letterA = 'A';
  • Just like numerical types, we can combine declaration and assignment into one statement:
    char letterB = 'B';
  • C++ allows us to assign ASCII code numbers to char variables as well
    char letterC = 67;
    cout << letterC << endl;
    

Examples of Declaring and Assigning char Variables

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

int main()
{
    char letterA;
    letterA = 'A';
    char letterB = 'B';
    char letterC = 67; // 67 is ASCII for 'C'
    cout << letterA << letterB << letterC << endl;
    return 0;
}

User I/O with Type char

  • Like numbers, we can output type char using cout <<
    char letter = 'A';
    cout << letter << 'B' << endl;
    
  • Also, we can input type char using cin >>
    cin >> letter;
    cout << letter  << endl;
    

Simple Arithmetic

  • Since char data types are actually integer numbers, C++ lets us do simple arithmetic
  • For example we can add or subtract integer numbers like:
    char letterE = letterA + 4;
    char letterD = letterE - 1;
    cout << letterD << letterE << endl;
    

More Information

  • ASCII: ASCII Introduction and History from Harvard CS50.tv (8:02)

Check Yourself

  1. The type of delimiter used to enclose single characters of type char is the ________.
  2. The correct data type for a single character is ________.
    1. character
    2. char
    3. text
    4. string
  3. Which of the following correctly declares a variable for a single character and assigns it a value?
    1. char var = 'z';
    2. char var = 122;
    3. char var = "z";
    4. char var = 'a' + 25;
  4. Write the code to declare a char variable named myChar and assign it a value of 'A'.

    answer

  5. Write the code to input a single character from the keyboard and store it in a previously declared variable named myChar.

    answer

3.2.2: Introduction to Strings

  • In addition to single characters, computers can work with text strings
  • For example, in the following the characters between the double quotes are displayed as text:
    cout << "Hello World!" << endl;
  • Programmers refer to text like this as a string because it is composed of a sequence of characters that we "string together"
  • C++ provides the string data type so we can work with text
  • To work with the string type we may need to include the string library:
    #include <string>
    using namespace std;
    
  • This library is included automatically with <iostream> in our version of g++
  • Literal strings are enclosed in double quotes, which are not part of the string
  • For example:
    "Hello"  "b"  "3.14159"  "$3.95"  "My name is Ed"
  • Notice that the string "3.14159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently and we must use them in different ways
  • For instance, we cannot multiply the "3.14159" by 2, but we can when it is expressed as a double:
    cout << "3.14159" * 2; // NO!
    cout << 3.14159 * 2; // allowed
    

Check Yourself

  1. The type of delimiters used to enclose strings is the ________
  2. True or false: "A" and 'A' are the same.
  3. The name of the string library is ________.
  4. True or false: we can perform arithmetic operations on strings.

3.2.3: String Variables and Simple I/O

  • We declare and assign values to string variables like numeric types
  • For example:
    string firstName;             // declaration
    firstName = "Edward";         // assignment
    string lastName = "Parrish";  // declaration + assignment
    cout << firstName << " " << lastName << endl;
    

Simple I/O with Strings

  • Like numbers, we can output type string using cout <<
  • Also, we can input a string using cin >> stringName
  • For example:
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "You entered: " << name  << endl;
    
  • The cin statement assigns the user input to the string variable name
  • Note that only a single word can be entered using cin >> name
  • This is because cin >> name works as follows:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found

Check Yourself

  1. True or false: use a string variable rather than a char variable when you may need to store more than one character.
  2. Write the code to declare a string variable named myString and assign it a value of "Hi Mom!".

    answer

  3. Write the code to input a word from the keyboard and store it in a previously declared variable named myWord.

    answer

3.2.4: Output of Hard-to-Print Characters

  • We have been using cout << operator to output strings
  • However, some strings are more difficult to output than others
  • For example, what if we wanted to output : "Say, Hey!"
  • We could write a cout statement like:
    cout << "Say, "Hey!"" << endl;
    
  • How would the compiler treat the double-quote marks (") in the statement?
  • Some characters cannot be output directly in a string
  • Also, the first 32 ASCII characters are Teleprinter control characters
  • Some control characters are still used today such as newline characters
  • We need some way to output characters like control codes and double quotes (")

Escape Sequences

  • C++ can print control codes and some hard-to-print characters using escape sequences
  • A backslash (\) directly in front of some characters tell the compiler to escape from the normal interpretation
  • The following table lists some common nonprinting and hard-to-print characters:
Sequence Meaning
\a Alert (sound alert noise)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quote
\" Double quote
\ooo ASCII character in octal notation
\xhhh ASCII character in hexadecimal notation
  • Some examples:
    cout << "Say, \"Hey!\"" << endl;
    cout << '\a' << endl; // alert
    cout << '\n' << endl;
    cout << "Left \t Right" << endl;
    cout << "one\ntwo\x00Athree" << endl;
    cout << "0x00A" << endl;
    

Programming Style

Check Yourself

  1. True or false: an escape sequence is a series of characters that does not represent itself but is translated into a character code.
  2. Which of the following is an escape sequence?
    1. /n
    2. /t/n/t
    3. \n\t\"
    4. /\n
  3. Which of the following is a correct way to print: Say, "Heh"!?
    1. cout << "Say, "Hey!"" << endl;
    2. cout << \"Say, "Hey!"\" << endl;
    3. cout << "Say, \"Hey!\"" << endl;
    4. cout << "Say, \"Hey!"\" << endl;
  4. True or false: tab characters a bad idea in source code files because the code may not line up on different systems or with different editors.
  5. True or false: to avoid tab characters in your source code, set up your text editor to use spaces when pressing the tab key.

3.2.5: Joining Strings (Concatenation)

  • We can join two strings together using the '+' operator
  • The join operation is called concatenation
  • For example:
    string s1 = "Hello", s2 = "World!";
    string s3 = s1 + s2;
    cout << s3 << endl;
    
  • The string s3 now has the contents of both s1 and s2
  • We can also mix string variables and literal strings:
    string s1 = "Hello", s2 = "World!";
    string s3 = s1 + ", " + s2;
    cout << s3 << endl;
    
  • One or both strings surrounding the + must be a string variable
  • For instance, the following will NOT work:
    string greeting = "Hello" + " " + "World!"; // No!
    
  • However, this is not usually a problem because we can just make one long literal string:
    string greeting = "Hello World!";
    
  • In addition, we can concatenate string variables and characters:
    char letter = 'A';
    string s1 = "BC";
    s1 = letter + s1 + 'D';
    
  • However, we cannot concatenate strings with numbers
    string str = "abc";
    str = str + "1"; // allowed
    str = str + '1'; // allowed
    str = str + 1;   // NO
    str = str + 1.2; // NO
    

Check Yourself

  1. The operator used to join two strings is ________.
  2. The contents of s3 is ________ after the following code executes.
    string s1 = "Hi ", s2 = "Mom!";
    string s3 = s1 + s2;
    
  3. The result of trying to compile and run the following code is ________.
    string s1 = "Hi", s2 = "Mom!";
    string s3 = s1 + " " + s2;
    
  4. The result of trying to compile and run the following code is ________.
    string s1 = "Hi " + " " + "Mom!";
    

3.2.6: String Functions

  • Strings are a special type of variable called objects, which we will study in more detail later in the course
  • An object is a data type that can have functions associated with it
  • These functions are called member functions and are called using dot notation
  • The syntax for calling a member function of a string object is:
    stringName.functionName(arguments)
    
  • Where:
    • stringName: the name of the string variable
    • functionName: the name of the member function
    • arguments: the input values, if any
  • Once we create a string variable, we call (invoke) its member functions

Some Commonly-Used Functions

  • length(): Returns the number of characters in a string
    string str = "Hello";
    cout << "The number of characters is " << str.length()
         << ".\n";
    
  • substr(i, n): Returns a substring of length n starting at index i
    string greeting = "Hello, World!\n";
    string sub = greeting.substr(0, 4);
    cout << sub << endl;
    
  • The position numbers in a string start at 0. The last character is always one less than the length of the string
    H e l l o , W o r l d !
    0 1 2 3 4 5 6 7 8 9 10 11 12
  • string w = greeting.substr(7, 5);
    H e l l o , W o r l d !
    0 1 2 3 4 5 6 7 8 9 10 11 12

Example Using String Functions

  • Consider the problem of extracting the initials from a person's name
  • What would be an algorithm for solving this problem?
  • To implement this algorithm, we can use the string function substr()
  • The following program implements an algorithm for extracting the initials from a person's name
  • What other technique could we use to extract the initials?

Program to Create Initials

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

int main() {
    string first;
    string middle;
    string last;
    cout << "Enter your full name (first middle last): ";
    cin >> first >> middle >> last;
    string initials = first.substr(0, 1)
        + middle.substr(0, 1) + last.substr(0, 1);
    cout << "Your initials are " << initials << "\n";

   return 0;
}

Extracting the Last Characters

  • Note that we can extract the last few letters of a string without knowing its length ahead of time
    string word;
    cout << "Enter a word: ";
    cin >> word;
    int lastLetter = word.length() - 1;
    cout << "The last letter of the word is "
         << word.substr(lastLetter) << endl;
    
  • If we call substr() with just the starting index, it returns the trailing characters
  • This technique can be adjusted to extract the last few characters instead of just one character

Check Yourself

  1. True or false: an object is a data type that can have functions associated with it.
  2. To call a function that is part of an object, between the object name and the function name we code a ________.
  3. The following code displays ________.
    string message = "Hi mom!";
    cout << message.length();
    
    1. 2
    2. 6
    3. 7
    4. 9
  4. For the following string variable, write a statement that displays the first two characters.
    string message = "Hi mom!";
    

    answer

Exercise 3.2: Programming Strings (8m)

In this exercise we write an interactive program using strings that runs like this:

First name: Ed
Last name: Parrish
Welcome "Ed Parrish"!
Your initials: EP

Note that the underlined font shows what is typed by the user. 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 classmate or the instructor for help.

Specifications

  1. Copy the following program into a text editor, save it as nameapp.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. In main(), declare three string variables, firstName, lastName, fullName, like this:

    Listing of nameapp.cpp

  3. Add two statements: (1) to prompt the user for the data they should enter and (2) to collect the user input and store it in the firstName variable. For instance:
    cout << "First name: ";
    cin >> firstName;
    
  4. Add two more statements like these to collect the last name and store the input in the lastName variable.
  5. Write a line of code to concatenate (join) the first and last names and assign them to the variable fullName like this:

    Listing of nameapp.cpp

    For more information see section: 3.2.4: Joining Strings (Concatenation)

  6. Finally, add code to your program to output the fullName variable using cout:
    cout << "Full name: " << fullName << "!\n";
    
  7. Compile and run your program to make sure it works correctly like this:
    First name: Ed
    Last name: Parrish
    Full name: Ed Parrish!
    
  8. Some text characters are hard to print, like a double quote ("). To print these we must escape them from their special meaning by putting a backslash (\) in front of them. Put a double quote mark around the full name by changing the line printing the full name to:
    cout << "Welcome \"" << fullName << "\"!\n";
    

    For more information on escaping characters see section: 3.2.6: Output of Hard-to-Print Characters

  9. You can extract parts of a string variable using the substr() function. Extract the first letter from the first and last name to create initials with the following code:
    string initials = firstName.substr(0, 1)
        + lastName.substr(0, 1);
    cout << "Your initials: " << initials << endl;
    

    For more information about string functions see: 3.2.5: String Functions

  10. Compile and run your program to make sure it works correctly like this:
    First name: Ed
    Last name: Parrish
    Welcome "Ed Parrish"!
    Your initials: EP
    
  11. Save your source code file so you can submit it to Canvas as part of assignment 3.

When finished, please help those around you.

Completed Program

Once you are finished, your source code should look like the following:

Listing of nameapp.cpp

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 3.2.7: Summary.

3.2.7: Summary

  • A character is a letter, number or special symbol
  • We make character literals by enclosing a single character in single quotes
  • We declare character variables using char as the data type:
    char letter = 'A';
    
  • Each character is stored as a number, using its ASCII code
  • We can input and output char data using cin and cout like integer data types
  • We make string literals by enclosing characters in double quotes
  • We declare string variables using string as the data type:
    string s1 = "Hello Mom!";
  • To concatenate two strings, use the "+" operator:
    string s2 = s1 + " suffix";
  • Type string can be input and output with cin and cout
  • We use functions of the string object for some operations
  • We looked at the member functions:
    • length(): Returns the number of characters in a string
      string s = "Hello";
      cout << s.length() << endl;
      
    • substr(i, n): Returns a substring of length n starting at index i
      string greeting = "Hello, World!\n";
      string sub = greeting.substr(0, 4);
      cout << sub << endl;
      

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. What type of delimiters are used to enclose single characters of type char? (3.2.1)
  2. What code do you write to declare a char variable named myChar and assign it a value of 'A'? (3.2.1)
  3. What code do you write to input a single character from the keyboard and store it in a variable named myChar? (3.2.1)
  4. What type of delimiters are used to enclose strings? (3.2.2)
  5. Are "A" and 'A' the same? Why or why not? (3.2.2)
  6. When would you want to use a string variable rather than a char variable? (3.2.2)
  7. What code do you write to define a string variable named myString and assign it a value of, "Hi Mom!"? (3.2.3)
  8. What code do you write to input a word from the keyboard and store it in a variable named myWord? (3.2.3)
  9. What operator is used to join two strings? (3.2.4)
  10. For a string variable named str, what code do you write to determine the number of characters in the string? (3.2.5)
  11. What function do you use to find a substring in a string variable? (3.2.5)
  12. Certain characters like double-quote marks (") are hard to print. How do you output these characters in C++? (3.2.6)
  13. What is the escape sequence for a newline? (3.2.6)

3.3: Making Decisions

Learner Outcomes

At the end of the lesson the student will be able to:

  • Discuss what is meant by the term flow of control
  • Make use of relational expressions to make decisions
  • Implement decisions using if statements
  • Compare numbers, characters and strings
  • Develop strategies for processing input and handling errors

3.3.1: Relational (Comparison) Operators

  • A relationship is the way in which two values are connected
  • In computer science, relationships are constructed using relational operators
  • The 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
  • The following table shows the similarities and differences between algebra and C++

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.

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;
    

Activity (2m)

Formulate the following test conditions in C++, then check your answer by pressing the answer link.

answer
answer
answer
answer
answer
answer

More Information

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: Making Decisions with if-Statements

  • 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 selection statement, also known as a conditional statement
  • A selection 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
  • The == is the equality operator in C++

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.3.3: Comparing Characters and Strings

  • Character data can be compared using 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)
    
  • Remember that 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
  • Also 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;
    }
}

Comparing Strings

  • We can compare strings using relational operators as well
  • C++ compares two strings using lexicographical order (a.k.a. alphabetic order)
  • Lexicographical order means the comparison is based on the alphabetical order of component letters
  • For example, "car" is less than "cat":
    c a r
    c a t
  • Also, "car" is less than "card"
    c a r
    c a r d
  • We can test string comparisons in the following example program

Example Program Comparing Strings

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
#include<iostream>
using namespace std;

int main() {
    string strOne, strTwo;
    cout << "Enter two words separated by whitespace: ";
    cin >> strOne >> strTwo;
    if (strOne == strTwo) {
        cout << strOne + " == " + strTwo << endl;
    }
    if (strOne != strTwo) {
        cout << strOne + " != " + strTwo << endl;
    }
    if (strOne < strTwo) {
        cout << strOne + " < " + strTwo << endl;
    }
    if (strOne <= strTwo) {
        cout << strOne + " <= " + strTwo << endl;
    }
    if (strOne > strTwo) {
        cout << strOne + " > " + strTwo << endl;
    }
    if (strOne >= strTwo) {
        cout << strOne + " >= " + strTwo << endl;
    }
}

Check Yourself

  1. What is the result of evaluating the following relational expression? (answer)
    'A' < 'B'
  2. What is the result of evaluating the following relational expression? (answer)
    "A" < "B"
  3. Of the following pairs of strings, which comes first in lexicographic order for each of them?
    1. "Harry", "Potter" (answer)
    2. "Harry", "Hairy" (answer)
    3. "car", "C++" (answer)
    4. "car", "Car" (answer)
    5. "car model", "carburetor" (answer)

More Information

3.3.4: 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
  • We 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
  • 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.3: Guessing Game (6m)

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

Specifications

  1. Copy the following program into a text editor, save it as selection.cpp, and 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;
    }
    
  2. 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: 3.3.1: Making Decisions with if-Statements.

  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 section: 3.3.4: Using if-else Statements.

  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;
    }
    

    Checking user input is a common use of if statements.

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

  8. Submit your source code file as part of the next assignment.

When finished please help those around you.

3.3.5: Nested if Statements

  • Remember that an if-else statement will always execute either the if-clause of the else-clause
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • The test condition decides which clause will execute
  • Does does the following if-else statement produce the same results as the one above?
    if (7 != guess) {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    } else {
        cout << "*** Correct! ***\n";
    }
    
  • What has changed?

Nesting 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
  • Nesting can be used to test multiple conditions
  • The following code shows an example of nesting an 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

  • We can nest if statements in the else clause as well
  • For example, we can check for low and high values before declaring a value is correct
    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";
        }
    }
    
  • When nested in the else clause, a program can make only one selection among the alternatives
  • As soon as a condition is found to be 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

Example Showing a Nested if-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 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";
    }
    

3.3.6: Summary

  • By default, code executes sequentially: one statement after another from top to bottom within a function like main()
  • Sometimes we want to change this sequential flow
  • One way to change the flow is a selection statement, also known as a conditional statement or if-statement
  • A selection statement contains code that executes if and only if a test condition evaluates to true
  • An if statement has two parts: a test and a body
    if (test) {
       body with statements to execute
    }
    
  • For example, in the following the message is displayed if and only if the value of guess equals 7:
    if (7 == guess) {
      cout << "*** Correct! ***\n";
    }
    
  • The message does NOT display if the test condition evaluates to false
  • Adding an else-clause causes statements to execute when a test condition evaluates to false:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
    }
    

Relational Operators

  • Relational operators are a common way to create a test condition
  • Relational operators include:
    ==  !=  <   <=  >   >=
  • Relational operators can be used with numbers, characters and strings
  • However, both operands must be compatible types

relational expression

Nesting

  • 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

Check Yourself

As time permits, be prepared to answer these questions. More information is available by following the links after the question.

  1. What is meant by the term "flow of control"? (3.3.1)
  2. What is the default flow-of-control operation after a statement finishes executing? (3.3.1)
  3. What part of an if statement is indented? (3.3.1)
  4. What is wrong with each of the following if statements placed after the code: (3.3.1)
    int guess;
    cout << "Enter your guess: ";
    cin >> guess;
    
    1. if (7 == guess) then cout << "You guessed 7!\n";
    2. if (guess = 7) cout << "You guessed 7!\n";
    3. if ("7" == guess) cout << "You guessed 7!\n";
  5. What is a relational expression and why are they used? (3.3.2)
  6. Of the following pairs of strings, which comes first in lexicographic order? (3.3.3)
    1. "Harry", "Potter"
    2. "Harry", "Hairy"
    3. "car", "C++"
    4. "car", "Car"
    5. "car model", "carburetor"
  7. What is the value of x after the following code segment? (3.3.4)
    int x = 5;
    if (x > 3) {
        x = x - 2;
    } else {
        x = x + 2;
    }
    
  8. Does the syntax for an else clause include a test condition? (3.3.4)
  9. True or false? You can nest if statements in either the if clause, the else clause, or both. (3.3.5)
  10. If you have a series of test conditions, and only one can be correct, what is the sequence of if and else statements you should follow? (3.3.5)

3.4: Pair Programming

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe how to complete an assignment using pair programming
  • Discuss the pros and cons of pair programming

3.4.1: Introduction to 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

Roles

  • 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
  • Each person "drives" about half the time:
    • Physically get up and move positions when switching roles to emphasize the change

Working Together

  • More than 75% of your time must be spent working on the projects together
  • The objective is to work together and to learn from each other
  • You cannot divide the work into two pieces with each partner working on a separate piece
  • If you are not both engaged in the process, you will not learn the material
  • People who do not learn the material fail the course
  • More information: Pair Programming for Homework Assignments

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

Video Explaining Pair Programming (10m)

Fun with Pair Programming: a professionally developed video (10 minutes)

Fun with Pair Programming Worksheet: follow along during the video

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.4.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
  • 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 or work by yourself

The Rules of Pair Programming

Refer to the rules to verify you are pair programming correctly!

Pair Programming Non-Performance Indicators

  • Silence immediately indicates a lack of collaboration
  • Disengagement when one member does not pay attention or does something else like email or texting
  • One member observes and offers little comment as they "watch the master"

Check Yourself

  1. True or false: there are no rules in pair programming.
  2. Indicators of poor pair programming performance include ________.
    1. one member is not paying attention
    2. one member observes and offers little comment as they "watch the master"
    3. silence
    4. all of these
  3. True or false: the rules of pair-programming require you to use only one computer at a time to edit and compile code.

More Information

Exercise 3.4: Finding a Partner (10m)

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

Specifications

  1. We will divide into groups.
  2. Within your group, exchange names and email addresses, 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 assignment 3.

Wrap Up

Due Next:
A3-Strings and Conditions (2/15/17)
  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.
Last Updated: March 07 2017 @17:15:11