Schedule‎ > ‎

## 3.1: Variables Revisited

3.1.1: Review of Variable

### 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++:
CategoryTypical
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:
TypeTypical
Bytes
Use
`bool`1`true` or `false` value.
`char`1All ASCII characters.
`int`4Integers with a range from -2,147,483,648 to 2,147,483,647.
`unsigned int`4Integers with a range from 0 to 4,294,967,295.
`float`4Single-precision, floating-point numbers with 6 or 7 significant digits, +/- range, and exponents from about 10-45 to 1038.
`double`8Double-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;
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

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

LiteralData Type
'A' bool char double int
-213.555 bool char double int
42 bool char double int
42.0 bool char double int
true bool char double int
'Z' bool char double int
false bool char double int

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

### 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 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. Your instructor will hand out this assignment.  Click HERE if you were sick and missed class.
2. You will work with a partner,  but each student must turn in this assignment on their own paper.
3. After completing a problem and before continuing to the next, compare your answers with another student.
4. If there is a disagreement, ask the instructor for clarification.
5. Repeat for the remaining exercise problems.

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

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

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

• 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'`.
5. 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` 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!"`.
3. Write the code to input a word from the keyboard and store it in a previously declared variable named `myWord`.

### 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:
SequenceMeaning
`\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;
```

#### 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(in): 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 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!";
```

### Exercise 3.2: Programming Strings (8m)

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

```First name: Maria
Last name: Vega
Welcome "Maria Vega"!
```

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. Go to the top of the class schedule page and copy the header template into a file and name it nameapp.cpp
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: Maria
Last name: Vega
Full name: Maria Vega!
```
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.  Print out the initials.

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: Maria
Last name: Vega
Welcome "Maria Vega"!
```
11. Save your source code file  nameapp.cpp and submit it to Canvas under Exercise 3.2.

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(in): 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 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:

• 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

MathNameC++Examples  ResultNotes
=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.

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

 x is positive x is negative x is zero x is zero or negative x is not equal to y x is greater than y plus one

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

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

#### 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. 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 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 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?
`'A' < 'B'`
2. What is the result of evaluating the following relational expression?
`"A" < "B"`
3. Of the following pairs of strings, which comes first in lexicographic order for each of them?
1. `"Harry", "Potter"`
2. `"Harry", "Hairy"`
3. `"car", "C++"`
4. `"car", "Car"`
5. `"car model", "carburetor"`

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

• 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 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
• 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?
```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?
```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"
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?

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?

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;    //-1 is often used as an error return code
}
```

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?

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

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

8. Add another if statement to check to see if the user input is larger than 10 and print an appropriate error message if the user input is larger than 10.
9. Submit your source code file selection.cpp to Canvas Ex. 3.3.

### 3.3.5: Nested `if` Statements

• Remember that an `if-else` statement will always execute if either the `if`-clause of the `else`-clause are true
```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 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 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 style shows more clearly that we are making a single choice among multiple alternatives
• Also, it prevents indentations from cascading to the right as we add more selections
• Optionally, we may put the opening curly brace on the same line as the test condition
```if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
```

#### Check Yourself

1. True or false: you can nest `if` statements in the `if` clause, the `else` clause, or both.
2. In the following code snippet, the `if (guess < 7)` is nested in the ________
1. the outer if-statement
2. the outer else clause
3. the inner if-statement
4. the inner else clause
```if (guess != 7)
{
if (guess < 7)
{
cout << "Your guess is too low.\n";
}
else
{
cout << "Your guess is too high.\n";
}
} else {
cout << "*** Correct! ***\n";
}
```
3. In the following code snippet, the `if (guess > 7)` is nested in the ________
1. the outer if-statement
2. the outer else clause
3. the inner if-statement
4. the inner else clause
```if (guess < 7)
{
cout << "Your guess is too low.\n";
}
else if (guess > 7)
{
cout << "Your guess is too high.\n";
}
else
{
cout << "*** Correct! ***\n";
}
```
4. True or false: in the above sequence of if-else statements, the final else clause belongs to the first if-statement.
5. True or false: if you have a series of test conditions, and only one can be correct, the following is a good style for your code's structure.
```if (guess < 7)
{
cout << "Your guess is too low.\n";
}
else if (guess > 7)
{
cout << "Your guess is too high.\n";
}
else
{
cout << "*** Correct! ***\n";
}
```

### Exercise 3.4 if-else-if

Specifications:
2.Save it as nested.cpp    (Make sure it compiles & runs)
3.You will check to see if the guess is between 1 and 10 using an if-else-if
4.Pseudocode is:
a)If guess < 1  print “Error: guess must be >=1” and

return -1

b)Otherwise if guess > 10 print “Error: guess must be <=10”  and return -1
c)Otherwise print:  “Your guess is within bounds
5.Make sure your if-else-if is properly formatted (See Key Sample Code at top of Schedule Page)
6.Test your code by entering -1, 12, 8, 7
7.What should print with each entry?  does it?
8.Submit your nested.cpp to Canvas Ex 3.4

### Completed nested.cpp

`#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;`
`    if (guess < 1)`
`    {`
`        cout << "Error: guess must be >= 1\n";`
`        return -1;`
`    } else if (guess > 10)`
`    {`
`        cout << "Error: guess must be <= 10\n";`
`        return -1;`
`    }  else  `
`    {`
`        cout << "Your guess is within bounds" << endl; `
`    }`
`    if (7 == guess)`
`    {`
`        cout << "*** Correct! ***" << endl;`
`    }`
`    else`
`    {`
`        cout << "Sorry, that is not correct.\n";`
`        cout << "Rerun and try again.\n";`
`    }`

`    return 0;`
`}`

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

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

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)

Subpages (1):