# 3. Arithmetic, Strings and Selection

## Continuations

#### Homework Discussion Questions

1. What was the hardest part of writing the code to implement your algorithm?
2. How useful was the example executable file for determining how the program operated?
3. How did you keep the line length to 80 characters or less?
4. What was the most informative CodeLab tutorial 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
• 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 using namespace std; int main() { cout << "Hello, World!\n"; return 0; } ```

3. Select Compile C++
4. If there are any syntax errors, you will see a page or area showing them

3. Select Run C++ Application
4. Your program will run in a console window

## 3.1: Numbers and Arithmetic

### Learner Outcomes

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

• Distinguish between an integer and a floating-point number
• Write C++ code for arithmetic expressions
• Infer the type returned from a mixed-mode arithmetic expression
• Construct expressions that use mathematical functions

### 3.1.1: Algorithms Using Numbers and Arithmetic

• Many problems can be solved using mathematical formulas and numbers
• Consider the simple problem of adding up all the coins in your pocket to get the total value in dollars
• What would be an algorithm for solving this problem?
• To implement this algorithm, we will need to use numbers and arithmetic
• As we saw before, C++ has two general types of numbers: integers and floating-point
• An integer is zero or any positive or negative number without a decimal point
• For example:
`0   1   -1    +5    -27   1000    -128`
• We call numbers like these literal integers because they stand for what they look like
• A floating-point number is any signed or unsigned number with a decimal point
• For example:
`0.0   1.0   -1.1   +5.   -6.3    3234.56    0.33`
• Note that `0.0`, `1.0` and `+5.` are floating-point numbers, but could be rewritten as integers
• In C++, both integers and floating-point numbers cannot have any commas or special symbols
• The following program implements an algorithm for summing coins
• Which variables are integers and which are floating-point numbers?

#### Program coins.cpp to Sum Coins

 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ``` ```#include using namespace std; int main() { int pennies = 8; int nickels = 5; int dimes = 4; int quarters = 3; double total = pennies * 0.01 + nickels * .05 + dimes * 0.10 + quarters * 0.25; cout << "Total value = " << total << "\n"; return 0; } ```

#### Check Yourself

1. The two types of numbers in C++ are ________ and ________.
2. Of the following literal numbers, ________ is an integer.
1. `1`
2. `1.2`
3. `1.23`
4. `1.234`
3. A literal number is ________.
1. a variable
2. an arithmetic operation
3. characters in double quotes
4. written in the usual way
4. For the following code, the left-hand side of the equals sign (=) is a ________ and the right-hand side is a ________ number.
```int pennies = 8;
```

### 3.1.2: Arithmetic

• C++ uses the following operators for arithmetic:
• `+` for addition
• `-` for subtraction
• `*` for multiplication
• `/` for division
• `%` for modulus (remainder after division)
• As in algebra, multiplication and division are performed before addition and subtraction
• To change the order of operation, you use parentheses
• For example:

is written as: `a + b / 2`

is written as: `(a + b) / 2`

1. You can use parentheses to group expressions
• Anything within the parentheses is evaluated first
`2 * (10 + 5)`
2. You can have parentheses within parentheses
• Innermost parenthesis evaluated first
`(2 * (10 + 5))`
3. Parentheses cannot be used to indicate multiplication
• Invalid expression: `(2)(3)`
• Must use the `*` operator

#### Programming Style

• Programming style: add spaces around binary operators
• `2 + 3`, not `2+3`
• Programming style: no spacing after opening or before closing parenthesis
• `(2 / 3)`, not `( 2/3 )`

We explore how you can use numbers and arithmetic in the following exercise.

#### Check Yourself

1. The five arithmetic operators in C++ are ________.
1. `+, -, /, *, %`
2. `+, -, \, *, %`
3. `+, -, /, *, ^`
4. `+, -, \, *, ^`
2. The first operation performed in the following arithmetic expression is ________.
```1 + 2 * 3 / 4 % 5
```
3. If we wanted a different ordering of operations in the above example, we add ________ to the expression.

### Exercise 3.1

Through the miracles of computer science, we will now convert your \$1000 computer into a \$10 calculator! Along the way, we learn how to work with arithmetic using C++.

#### Specifications

1. Type the following program into a text editor, save it as arithmetic.cpp, and then compile and run the starter program to make sure you typed it correctly.

2. In `main()`, declare two `double` variables named `a` and `b`, and assign them a value of `7` and `2` respectively. For instance:
`double a = 7, b = 2;`
3. Add a line of code to display the arithmetic expression `(a + b)` and then recompile and run the program.
```cout << "a + b = " << a + b << endl;
```

The output when you run the program should look like this:

```a + b = 9
```

If you do not see this output, please ask a classmate or the instructor for help.

4. Add three more lines of code like the previous one that computes the expressions: `a - b`, `a * b` and `a / b`. Compile and run your program again and make sure your program now displays the following output:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3.5
```
5. The order of operations matters in C++ just like it does in algebra. Multiplication and division are performed before addition and subtraction. Add the following two statements to your program:
```cout << "a + b / 2 = " << a + b / 2 << endl;
cout << "(a + b) / 2 = " << (a + b) / 2 << endl;
```
6. Compile and run your program again and compare the output. Your program should now display the following output:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3.5
a + b / 2 = 8
(a + b) / 2 = 4.5
```

Note how the output of the two statements is different. You can change the order of operation using parenthesis, just like in algebra. For more information on the order of operations see section: 3.1.2: Arithmetic.

As you can see, arithmetic in C++ works much like you would expect. However, there are some mysteries when working with integer variables which we will now explore:

• Truncation in integer division
• Modulus (%) operator

7. Truncation in integer division: Change the data type of the two variables from `double` to `int`, like this:
`int a = 7, b = 2;`
8. Compile and run your program again and compare the output. Note how the result of the division operation changed. What happened to the decimal part of the result?

In programming terms, we say that the decimal part is truncated (cut short). You have to watch out for this in C++ programming or you may get unexpected results in your calculations. For more information see section: 3.1.4: Integer Division and Modulus.

9. Modulus (%) operator: Sometimes we want the integer remainder from an integer division. To see the integer remainder, we use the modulus (%) operator. Add the following statement to your program:
```cout << "a % b = " << a % b << endl;
```
10. Compile and run your program again with this added statement. Your program should now display the following output:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3
a + b / 2 = 8
(a + b) / 2 = 4
a % b = 1
```

For more information on the modulus operator see section: 3.1.4: Integer Division and Modulus.

11. Mathematical functions: More complex mathematical operations require the use of a function in C++. one such function is `sqrt(number)` which calculates the square root of the number inside the parenthesis. Add the following statement to your program:
```cout << "sqrt(a + b) = " << sqrt(a + b) << endl;
```
12. You program will not compile with this new statement because you must include a library of the mathematical functions. Add the statement: `#include <cmath>` to the top of your program like this:
```#include <iostream>
#include <cmath> // math function library
using namespace std;
```
13. Compile and run your program again with this added statement. Your program should now compile and display the following output when run:
```a + b = 9
a - b = 5
a * b = 14
a / b = 3
a + b / 2 = 8
(a + b) / 2 = 4
a % b = 1
sqrt(a + b) = 3
```

14. Save your program source code that displays all eight (8) expressions so you can submit it to Blackboard as part of assignment 3.

#### Completed Program

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

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

### 3.1.3: Mixed-Mode Expressions

• Recall that different data types are stored in different forms
• An `int` is stored in 4 bytes
• A `double` is stored in 8 bytes
• The format they are stored in is different as well
• The computer needs both operands in the same form before it can perform an operation
• If one operand is different than the other, the compiler converts it to the wider of the two types
• For example:
`2 + 2.3`
• First number (`2`) is an `int`
• Second number (`2.3`) is a `double`
• C++ will automatically convert an `int` to a `double`
• Then the arithmetic operation can take place to produce a result of `4.3`
• Remember that the result of arithmetic with an `int` and a `double` is a `double`

#### Check Yourself

1. The result of adding an integer with a double in the following expression is ________.
`1 + 2.3`
2. In the above expression, C++ converts the integer `1` to type ________.
3. The data type of the number returned by the following expression is ________.
`3 + 4.5`

### 3.1.4: Integer Division and Modulus

• Dividing two integers can produce unexpected results for the unwary
• In division, if at least one of the numbers is a floating-point number, the result is a floating point number:
```7.0 / 2.0   // 3.5
7 / 2.0     // 3.5
7.0 / 2     // 3.5
```
• However, if both numbers are integers, then the result is an integer:
```7 / 2       // 3
```
• The decimal remainder is truncated (cut short, discarded, thrown away)
• To get the integer remainder of division between two integers, you use the modulus operator: %
```7 % 2       // 1 (remainder)
```
• `7 % 2` returns `1` because `1` is the remainder when `7` is divided by `2`:
```    3  r 1
2 ) 7
-6
1 remainder
```
• For a refresher on remainders see: Long Division with Remainders

#### Check Yourself

1. In division between two integer numbers, the remainder is ________.
2. Use the operator ________ to compute the integer remainder.
3. What is the result of the following arithmetic operations?

### 3.1.5: Mathematical Functions

• Operators provide only the simplest mathematical operations
• For more complex operations, we use mathematical functions
• A C++ function is like a mathematical function that takes an argument ("input") and produces ("returns") a value
• For example:
`cout << sqrt(9.0) << endl;`
• In the above example, the input is `9.0` and the `sqrt()` function returns the square root of the argument
• C++ has a standard library named cmath that contains many such functions
• Some of the functions are listed below
• Note that many of these functions are designed to work with floating-point date types like `double`
• For example, `pow()` will not compile if the first term is not a floating-point number
Name Description Example Result
fabs absolute value `fabs(-3.9)`
`fabs(3.9)`
`3.9`
`3.9`
exp exponent (ex) `exp(1.0)` `2.71828`
log natural log `log(10.0)` `3.10259`
pow powers (xy) `pow(2.0, 3.0)` `8`
sqrt square root `sqrt(4.0)` `2`
sin sine `sin(0)` `0`
cos cosine `cos(0)` `1`
• In addition, the `cmath` library includes two similar functions: `ceil`, and `floor`
Name Description Example Result
ceil ceiling: round up `ceil(3.3)`
`ceil(3.7)`
`4`
`4`
floor floor: round down `floor(3.3)`
`floor(3.7)`
`3`
`3`
• Both return whole numbers, although they are of type `double`

#### Using Mathematical Functions

• How are mathematical functions evaluated?
• Whatever is within the parenthesis of the function call is evaluated first
• Thus, in the following example, we get the square root of `9.0`
`cout << sqrt(3.0 * 3) << endl;`
• If the function is used in an arithmetic expression, they are handled just like a number of the type returned
• For example, in the following, the value `4.0` is stored in the double variable `num`:
```double num = 1 + sqrt(3.0 * 3.0);
cout << num << endl;
```
• Note that the function evaluates the `sqrt(3.0 * 3)` before adding it to `1.0`
• Thus functions have a higher precedence than arithmetic operators

#### Check Yourself

1. A C++ mathematical function take an ________ and returns a value.
2. The name of the library that contains many common mathematical functions is ________
3. Enter the code to calculate the square root of the number `49`.

4. To round up a number, call the mathematical function ________.
5. Use a ________ to save the result of a mathematical function.

### 3.1.6: Summary

• C++ uses the following operators for arithmetic:
• `+` for addition
• `-` for subtraction
• `*` for multiplication
• `/` for division
• `%` for modulus (remainder)
• As in algebra, multiplication and division are performed before addition and subtraction
• To change the order of operation, you use parenthesis
• The results of integer division are truncated
• You must use modulus operator (`%`) to get the remainder value
• More complex mathematical operations are available using the cmath library
`cout << sqrt(3.0 * 3) << endl;`

#### Check Yourself

1. How can you tell the difference between an integer and a floating-point number? (3.1.1)
2. What are the five operators C++ provides for arithmetic? (3.1.2)
3. What is the first operation performed in the expression: `1 + 2 * 3 / 4 % 5`? (3.1.2)
4. What is the data type returned by the following expression? (3.1.3)
`3 + 4.5`
5. What happens to the remainder during integer division? (3.1.4)
6. What operator can you use to compute the integer remainder? (3.1.4)
7. What is the result of the following arithmetic expressions? (3.1.4)
```5 / 4
5 % 4
```
8. What is a function? (3.1.5)
9. What code do you write to calculate the square root of the number `49`? (3.1.5)

## 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
• You 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'   '\$'   '*'`
• When you use a char data type, you store the character using an ASCII code
• ASCII is a coding method that assigns a number to every character
• You can see the codes in an ASCII Table

#### Declaring and Assigning `char` Variables

• As with other data types, you must declare `char` variables before use:
`char letter;`
• You assign values to a char variable using the equals sign:
`letter = 'A';`
• Just like numerical types, you can combine declaration and assignment into one statement:
`char letter = 'A';`
• Also like numerical types, you can declare multiple variables on one line:
`char letter, letterA = 'A', letterB = 'B';`

#### User I/O with Type char

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

#### Check Yourself

1. The type of delimiter used to enclose single characters of type `char` is the ________.
2. True or false: "A" and 'A' are the same type.
3. Write the code to declare a `char` variable named `myChar` and assign it a value of `'A'`.

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

### 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` type so we can work with text
• To work with the `string` type you need to include the `string` library:
```#include <string>
using namespace std;
```
• This library is included automatically with `<iostream>` in our version of `g++`
• 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 ________.

### 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, you can output type `string` using `cout <<`
• Also, you 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!"`.

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

### 3.2.4: Joining Strings (Concatenation)

• You 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`
• You 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!";
```

#### 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.5: 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 you create a `string` variable, you can use 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` `!` `\n` 0 1 2 3 4 5 6 7 8 9 10 11 12 13
• `string w = greeting.substr(7, 5);`
 `H` `e` `l` `l` `o` `,` ` ` `W` `o` `r` `l` `d` `!` `\n` 0 1 2 3 4 5 6 7 8 9 10 11 12 13

#### 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 intials from a person's name
• What other technique could you 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 #include 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; } ```

#### 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, put a ________ between the object name and the function name.
3. For a `string` variable named `str`, write the code to determine the number of characters in the string.

4. To find a substring in a `string` variable, call the function ________.

### 3.2.6: Output of Hard-to-Print Characters

• We have been using the `<<` operator to output strings
```string msg = "Hello Mom!";
cout << msg << endl;
```
• However, some characters are more difficult to output than others
• For example, what would the compiler do with the following statement?
`cout << "Say, "Hey!"" << endl;`
• Some characters cannot be output directly in a string
• Also, the first 32 ASCII characters are not visible on our monitors
• Known as control characters because they control the output device
• Even though these characters are not visible, we sometimes need to use them
• For example, a newline character
• We need some way to "print" invisible and hard-to-print characters

#### Escape Sequences

• C++ can access control codes and hard-to-print characters using escape sequences
• Backslash (`\`) directly in front of a certain character tells the compiler to escape from the normal interpretation
• The following table has some 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 << '\a' << endl; // alert
cout << '\n' << endl;
cout << "Left \t Right" << endl;
cout << "one\ntwo\nthree" << endl;
```

#### Programming Style

We explore how you can use strings in the next exercise.

#### Check Yourself

1. Certain characters like double-quote marks (`"`) are hard to print. To output these characters in C++ use a(n) ________ character.
2. True or false: the escape sequence for a newline is \x.
3. 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.

### Exercise 3.2

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

```First name: Ed
Last name: Parrish
Welcome "Ed Parrish"!
```

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 the 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() {

return 0;
}
```
2. In `main()`, declare three `string` variables, `firstName`, `lastName`, `fullName`, like this:

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:

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"!
```
11. Save your source code file so you can submit it to Blackboard as part of assignment 3.

#### Completed Program

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

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
• You make character literals by enclosing a single character in single quotes
• You declare character variables using `char` as the data type:
```char letter = 'A';
```
• Each character is stored as a number, using its ASCII code
• You can input and output `char` data using `cin` and `cout` like integer data types
• You make string literals by enclosing characters in double quotes
• You 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`
• You 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

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 Computers Smart

### 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: Teaching Computers to Make Decisions

• The programs we have worked with so far simply execute a list of instructions
• We arrange our command statements in a particular order to get the result we want
• When the program reaches the end of the list of instruction, it stops
• Except for differences in the input, these programs always work the same way
• To create more interesting and useful programs, we need our programs to make decisions and carry out different actions
• For example, if the user enters an incorrect value, we want our program to warn the user with an error message
• However, if the user enters a correct value, we do not want to display an error message
• For our programs to make decisions and carry out different actions, we use statements to change the flow of control
• Flow of control (or control flow) refers to the order in which programs execute instructions
• By changing the flow of control based on a test condition, we can teach the computer to make decisions
• We will look at two major ways to change the flow of control:
• Conditional (selection) statements
• Loops (repetition) statements
• In this section, we will look at how to use the conditional statements:
```if
if...else
```
• Later will look at more selection statements and how to use the loop statements

#### Check Yourself

1. True or false: the default behavior for a computer program is to execute statements sequentially.
2. To change the flow of a program, we use a ______ flow statement such as an if-statement.
3. The two general control flow statements will we examine in this course are ________ and ________.

### 3.3.2: The Value of a Relationship

• Before we discuss if-statements we need to talk about relationships
• A relationship is a way to compare two numbers or other entities
• For example:

• 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 C++ relationships are similar
• The following table shows the relational operators of C++

#### Relational Operators

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

#### Check Yourself

Formulate the following test conditions in C++:

### 3.3.3: Using `if` Statements

• The simplest control-flow statement is an `if` statement
• We use an `if` statement to select whether or not to execute a set of statements
• 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
• For example:
```if (7 == guess) {
cout << "*** Correct! ***" << endl;
}
```
• For clarity:
• Write the `if` on a different line than the executed block
• Indent statements 3-4 spaces within the curly braces
• You can see an example of an `if` statement in the following example

#### Example Program With an `if` Statement

 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ``` ```#include 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; } ```

• 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

#### Check Yourself

1. To execute statements only when a certain condition is true, use an ______ statement.
2. What is wrong with each of the following `if` statements placed after the code:
```int guess;
cout << "Enter your guess: ";
cin >> guess;
```
1. `if (7 == guess) then cout << "You guessed 7!\n";` (answer)
2. `if (guess = 7) cout << "You guessed 7!\n";` (answer)
3. 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)`
4. True or false: an if-statement affects only the single statement following it unless curly braces are used.

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

#### Example Program With an `if-else` Statement

 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ``` ```#include using namespace std; int main() { int guess = 0; cout << "I'm thinking of a number between" << " 1 and 10.\nCan you guess it?\n\n" << "Enter your guess: "; cin >> guess; if (7 == guess) { cout << "*** Correct! ***\n"; } else { cout << "Sorry, that is not correct.\n"; cout << "Try again.\n"; } return 0; } ```

#### Formatting the `if` Statement

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

### 3.3.5: Comparing Characters and Strings

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

#### Example Program Comparing Characters

 ```1 2 3 4 5 6 7 8 9 10 11 12 ``` ```#include using namespace std; int main() { cout << boolalpha; // output true or false cout << "'A' < 'B': " << ('A' < 'B') << endl; cout << "'A' > 'B': " << ('A' > 'B') << endl; cout << "'A' <= 'Z': " << ('A' <= 'Z') << endl; cout << "'X' >= 'Y': " << ('X' >= 'Y') << endl; cout << "'X' == 'X': " << ('X' == 'X') << endl; cout << "'X' != 'X': " << ('X' != 'X') << endl; } ```

#### Comparing Strings

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

#### Example Program Comparing Strings

 ```1 2 3 4 5 6 7 8 9 10 11 ``` ```#include using namespace std; int main() { string s1, s2; cout << "Enter two strings: "; cin >> s1 >> s2; cout << boolalpha; // output true or false cout << "s1 <= s2: " << (s1 <= s2) << endl; cout << "s1 > s2: " << (s1 > s2) << endl; } ```

#### 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)

### Exercise 3.3

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"
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.2: Using `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?

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 need to replace our `if` statement with an `if-else` statement like:
```if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
}
```

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

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. This type of code is known as input validation or input verification.

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?

You entered: 0
Error: guess must be >= 1
```

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

8. You can nest `if` statements inside either the `if` or `else` clause. We can use this when we have a series of tests to make. Replace all the `if` and `if-else` statements with the following code:
```if (guess < 1) {
cout << "Error: guess must be >= 1\n";
} else if (guess > 10) {
cout << "Error: guess must be <= 10\n";
} else if (guess != 7) {
cout << "Sorry, that is not correct.\n";
} else {
cout << "*** Correct! ***\n";
}
```

Conditions are checked in order until the one of the conditions evaluates to true. Once one condition evaluates to true, the rest of the tests are skipped. If no test condition evaluates to true then the `else` clause executes as the default case. For more information, see section: 3.3.6: Nested `if` Statements.

9. Compile your program and run it several times to see what message you get when you enter each of the following as a guess:
1. `0`
2. `7`
3. `9`
10. Review the purpose of each line of code with another student in the class. Then add a comment to the top of the file that contains the name of the person with whom you reviewed the code, like:
```// Reviewed with Jane Programmer
```
11. Save your source code file so you can submit it to Blackboard as part of assignment 3.

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

### 3.3.6: Nested `if` Statements

• Note that you can include `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`
• The following code shows an example of a nested if statement

#### Example Showing a Nested `if` Statement

 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ``` ```#include using namespace std; int main() { int guess = 0; cout << "I'm thinking of a number between" << " 1 and 10.\nCan you guess it?\n\n" << "Enter your guess: "; cin >> guess; if (guess != 7) { if (guess < 7) { cout << "Your guess is too low.\n"; } else { cout << "Your guess is too high.\n"; } } else { cout << "*** Correct! ***\n"; } return 0; } ```

#### Nesting in the `else` Clause

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

#### Example Showing a Nested `else if` Statement

 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ``` ```#include 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
```if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
```
• This shows more clearly that we are making a single choice among multiple alternatives
• Also, it prevents indentations from cascading to the right as we add more selections

#### 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 structure for your code.
```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.7: Summary

• All selection and repetition statements have a test condition
• This test condition controls the operation of the statement
• Relational operators are a common way to create a test condition
• In this section we looked at how to implement decisions using an `if` statement
• An `if` statement has two parts: a test and a body
• For example:
```if (7 == guess) {
cout << "*** Correct! ***" << endl;
}
```
• The `if` statement executes a block of code only if the test evaluates to true
• It does nothing if the conditional expression evaluates to false
• We can execute statements when the condition is false by using an else clause
• For example:
```if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
}
```
• We often implement test conditions using relational operators to create a relational expression
• Relational operators include:
`==  !=  <   <=  >   >=`
• We can use these relational operators with numbers, characters and strings
• One common use of `if` statements is validation of user input
• We can test the type of the input by using:
`if (cin.fail())`
• We looked at alternate strategies for testing the input type as well
• In addition to checking the type, good programs validate the input values
• For instance, if we want the user to enter a number greater than or equal to 1:
```if (guess < 1) {
cout << "Error: guess must be >= 1\n";
return 1;
}
```
• Also we noted that you can nest if statements within another `if` or `else`

#### Check Yourself

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.2)
4. What is the value of `x` after the following code segment? (3.3.2)
```int x = 5;
if (x > 3) {
x = x - 2;
} else {
x = x + 2;
}
```
5. What is wrong with each of the following `if` statements placed after the code: (3.3.2)
```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";`
6. Does the syntax for an `else` clause include a test condition? (3.3.3)
7. What is a relational expression and why are they used? (3.3.4)
8. What is the output of the following code fragment? Why? (see textbook pg. 86)
```cout.precision(17);
double r = sqrt(2);
if (r * r == 2) {
cout << "sqrt(2) squared is 2\n";
} else {
cout << "sqrt(2) squared is not 2 but "
<< (r * r) << endl;
}
```
9. For the above example code fragment, what is a better test condition than `(r * r == 2)`?
10. Of the following pairs of strings, which comes first in lexicographic order? (3.3.5)
1. `"Harry", "Potter"`
2. `"Harry", "Hairy"`
3. `"car", "C++"`
4. `"car", "Car"`
5. `"car model", "carburetor"`
11. True or false? You can nest `if` statements in either the `if` clause, the `else` clause, or both. (3.3.6)
12. 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.6)

## 3.4: Pair Programming

### Learner Outcomes

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

• Describe the steps for writing a program
• Discuss the pros and cons of pair programming

### 3.4.1: Solo Development Problems

• Developing programs on your own is often difficult
• Sometimes you do not know where to start
• While developing, you run into problems you must solve
• You can get some help from others without cheating (see Working Together)
• However, you have to write all the code on your own
• When you write code, you produce many bugs without noticing them
• Then you test your program and find it does not work correctly
• Sometimes, you just cannot see the problem in your program
• It seems there must be a better way to learn programming
• One solution is to use pair programming

### 3.4.2: 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 using the mouse and keyboard is called the driver
• The person reviewing is called the navigator
• In addition to reviewing, the navigator:
• Analyzes the design and code to prevent errors
• Looks up reference materials like program syntax
• Each person "drives" about half the time:
• Physically get up and move positions when switching roles
• At most 25% of your time is spent working alone:
• Any work done alone is reviewed by the other person
• 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

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

### 3.4.3: Best Practices

• You may choose any other student in this class for a partner
• You may NOT program with a person from another 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
• You should find a partner with whom you can easily exchange ideas
• If you cannot work easily with someone, you should get another partner or work by yourself

### 3.4.4: Summary

• Programming is about solving problems using a computer program
• Generally, you should develop programs in two phases:
1. Problem-solving phase: the output is a working algorithm
2. Implementation phase: the output is a working program
• Since defining problems, developing algorithms and implementing algorithms is hard, you can work with a partner
• Use some care when choosing a pair-programming partner to maximize your success
• In addition, both you and your partner should read: All I Really Need to Know about Pair Programming I Learned In Kindergarten

#### Check Yourself

1. What are three problems with solo programming? (3.4.1)
2. What are the rules of pair programming? (3.4.2)
3. Why should you change who is driving when you pair-program? (3.4.2)
4. What are the jobs of the navigator? (3.4.2)
5. How do you make sure that both people learn the material when pair programming? (3.4.2)
6. Why do the rules of pair-programming require you to use only one computer at a time to edit and compile code? (3.4.2)
7. What is the key factor for success in using pair programming? (3.4.3)

### Exercise 3.4

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

#### Specifications

1. We will count off and divide into separate 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 programming knowledge
3. Can program in another programming language
4. Can program 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 Blackboard as part of assignment 3.

## Wrap Up

Due Next:
A2-Implementing an Algorithm (2/23/12)
A3-Three Easy Programs (3/1/12)