What We Will Cover
Continuations
Questions from last class or reading?
Homework Questions?
Homework Discussion Questions
- What was the hardest part of writing the code to implement your algorithm?
- How useful was the example executable file for determining how the program operated?
- How did you keep the line length to 80 characters or less?
- 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 <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
}
|
Compiling with TextPad
- Load your source code into the active TextPad window
- Select the Tools menu
- Select Compile C++
- If there are any syntax errors, you will see a page or area showing them
- Otherwise, you will return to your source code page
Running Programs with TextPad
- Load your source code into the active TextPad window
- Select the Tools menu
- Select Run C++ Application
- Your program will run in a console window
^ top
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
|
^ top
3.1.1: Algorithms Using Numbers and Arithmetic
Program coins.cpp to Sum Coins
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <iostream>
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;
}
|
^ top
3.1.2: Arithmetic
Notes About Arithmetic
- You can use parentheses to group expressions
- Anything within the parentheses is evaluated first
2 * (10 + 5)
- You can have parentheses within parentheses
- Innermost parenthesis evaluated first
(2 * (10 + 5))
- Parentheses cannot be used to indicate multiplication
- Invalid expression:
(2)(3)
- Must use the
* operator
Programming Style
- Programming style: add spaces around binary operators
- Programming style: no spacing after opening or before closing parenthesis
We explore how you can use numbers and arithmetic in the following exercise.
^ top
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
- 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.

- 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;
- 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.
- 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
- 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;
- 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
- Truncation in integer division: Change the data type of the two variables from
double to int, like this:
int a = 7, b = 2;
- 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.
- 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;
- 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.
- 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;
- 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;
- 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
For more information on mathematical functions see section: 3.1.5: Mathematical Functions.
- Submit your program source code that displays all eight (8) expressions 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.
^ top
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 and
int to a double
- Then the arithmetic operation can take place to produce a result of
3.3
- Remember that the result of arithmetic with an
int and a double is a double
^ top
3.1.4: Integer Division and Modulus
Check Yourself
What is the result of the following arithmetic operations?
- 9 / 4
- 17 / 3
- 14 / 2
- 9 % 4
- 17 % 3
- 14 % 2
^ top
3.1.5: Mathematical Functions
| 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
^ top
3.1.6: Summary
Check Yourself
- How can you tell the difference between an integer and a floating-point number? (3.1.1)
- What are the five operators C++ provides for arithmetic? (3.1.2)
- What is the first operation performed in the expression:
1 + 2 * 3 / 4 % 5? (3.1.2)
- What is the data type returned by the following expression? (3.1.3)
3 + 4.5
- What happens to the remainder during integer division? (3.1.4)
- What operator can you use to compute the integer remainder? (3.1.4)
- What is the result of the following arithmetic expressions? (3.1.4)
5 / 4
5 % 4
- What is a function? (3.1.5)
- What code do you write to calculate the square root of the number
49? (3.1.5)
^ top
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
|
^ top
3.2.1: Type char
Declaring and Assigning char Variables
User I/O with Type char
^ top
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
^ top
3.2.3: String Variables and Simple I/O
Simple I/O with Strings
^ top
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!";
^ top
3.2.5: String 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 <iostream>
#include <string>
using namespace std;
int main() {
string first;
string middle;
string last;
cout << "Enter your full name (first middle last): ";
cin >> first >> middle >> last;
string initials = first.substr(0, 1)
+ middle.substr(0, 1) + last.substr(0, 1);
cout << "Your initials are " << initials << "\n";
return 0;
}
|
^ top
3.2.6: Output of 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 |
Programming Style
We explore how you can use strings in the next exercise.
^ top
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"!
Your initials: EP
Note that the underlined font shows what is typed by the user. As you work through the exercise, I suggest that you compile after each step so you know where the error is located if you make a mistake. Also, if you get stuck then ask a classmate or the instructor for help.
Specifications
- Copy the following program into a text editor, save it as
nameapp.cpp, and then compile and run the starter program to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
- In
main(), declare three string variables, firstName, lastName, fullName, like this:

- 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;
- Add two more statements like these to collect the last name and store the input in the
lastName variable.
- Write a line of code to concatenate (join) the first and last names and assign them to the variable
fullName like this:

For more information see section: 3.2.4: Joining Strings (Concatenation)
- Finally, add code to your program to output the
fullName variable using cout:
cout << "Full name: " << fullName << "!\n";
- Compile and run your program to make sure it works correctly like this:
First name: Ed
Last name: Parrish
Full name: Ed Parrish!
- 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
- 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
- Compile and run your program to make sure it works correctly like this:
First name: Ed
Last name: Parrish
Welcome "Ed Parrish"!
Your initials: EP
- Submit your program source code 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.
^ top
3.2.7: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- What type of delimiters are used to enclose single characters of type
char? (3.2.1)
- What code do you write to declare a
char variable named myChar and assign it a value of 'A'? (3.2.1)
- What code do you write to input a single character from the keyboard and store it in a variable named
myChar? (3.2.1)
- What type of delimiters are used to enclose strings? (3.2.2)
- Are "A" and 'A' the same? Why or why not? (3.2.2)
- When would you want to use a
string variable rather than a char variable? (3.2.2)
- What code do you write to define a string variable named
myString and assign it a value of, "Hi Mom!"? (3.2.3)
- What code do you write to input a word from the keyboard and store it in a variable named
myWord? (3.2.3)
- What operator is used to join two strings? (3.2.4)
- For a
string variable named str, what code do you write to determine the number of characters in the string? (3.2.5)
- What function do you use to find a substring in a
string variable? (3.2.5)
- Certain characters like double-quote marks (
") are hard to print. How do you output these characters in C++? (3.2.6)
- What is the escape sequence for a newline? (3.2.6)
^ top
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
|
^ top
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
^ top
3.3.2: Using if Statements
Example Program With an if Statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
if (7 == guess) {
cout << "*** Correct! ***" << endl;
}
return 0;
}
|
About those Curly Braces
- Technically, the
if statement affects only the single statement that follows
- We use curly braces to make that one statement into a block of statements
- This allows us to put any number of statements within the body
- Curly braces are not always required, but the best practice is to always include them
^ top
3.3.3: Using if-else Statements
- Sometimes we want to choose between two actions
- If a condition is true
- Otherwise it is false
- 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 <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
return 0;
}
|
Formatting the if Statement
^ top
3.3.4: The Value of a Relationship
- To make a selection we need to code a test condition
- The computer uses the test to decide whether or not to execute the statement
- One way to code a test condition is to write a relational expression
- A relational expression uses a relational operator to compare two entities like numbers or variables
- For example:

- You can see the relational operators of C++ in the following table
Relational Operators
| Math |
Name |
C++ |
Examples |
Result |
Notes |
| = |
Equal to |
== |
5 == 10 2 == 2 |
false true |
Do not confuse with = which is assignment. |
| ≠ |
Not equal to |
!= |
5 != 10 2 != 2 |
true false |
The ! is like the line that "crosses through" the equal sign. |
| < |
Less than |
< |
5 < 10 5 < 5 5 < 2 |
true false false |
|
| ≤ |
Less than or equal to |
<= |
5 <= 10 5 <= 5 5 <= 2 |
true true false |
Be careful not to write =<. Code the symbols in the order people normally say them. |
| > |
Greater than |
> |
5 > 10 5 > 5 5 > 2 |
false false true |
|
| ≥ |
Greater than or equal to |
>= |
5 >= 10 5 >= 5 5 >= 2 |
false true true |
Be careful not to write =>. Code the symbols in the order people normally say them. |
Check Yourself
Formulate the following test conditions in C++:
^ top
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<iostream>
using namespace std;
int main() {
cout << boolalpha; // output true or false
cout << "'A' < 'B': " << ('A' < 'B') << endl;
cout << "'A' > 'B': " << ('A' > 'B') << endl;
cout << "'A' <= 'Z': " << ('A' <= 'Z') << endl;
cout << "'X' >= 'Y': " << ('X' >= 'Y') << endl;
cout << "'X' == 'X': " << ('X' == 'X') << endl;
cout << "'X' != 'X': " << ('X' != 'X') << endl;
}
|
Comparing Strings
- We can compare strings using relational operators as well
- C++ compares two strings using lexicographical order (a.k.a. alphabetic order)
- For example, "car" is less than "cat":
- Also, "car" is less than "card"
Example Program Comparing Strings
1
2
3
4
5
6
7
8
9
10
11
|
#include<iostream>
using namespace std;
int main() {
string s1, s2;
cout << "Enter two strings: ";
cin >> s1 >> s2;
cout << boolalpha; // output true or false
cout << "s1 <= s2: " << (s1 <= s2) << endl;
cout << "s1 > s2: " << (s1 > s2) << endl;
}
|
More Information
^ top
Exercise 3.3
In this exercise we explore the use of relational operators with if statements to create a simple game.
Specifications
- Copy the following program into a text editor, save it as
selection.cpp, and then compile and run the starter program to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
cout << "You entered: " << guess << endl;
// Insert new statements here
return 0;
}
- 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.
- Compile and run your program again and verify the output looks like:
I'm thinking of a number between 1 and 10.
Can you guess it?
Enter your guess: 7
You entered: 7
*** Correct! ***
If you rerun the program and enter a number different than 7 (like 9) then the message saying correct will NOT appear.
- For a friendlier game output, we should give a message when the user enters an incorrect value. For this we need to replace our
if statement with an if-else statement like:
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Please try again.\n";
}
Statements inside the curly braces of the else clause only execute if the test condition in the parenthesis, (7 == guess), evaluates to false. For more information, see section: 3.3.3: Using if-else Statements.
- Compile and run your program again and verify the output looks like:
I'm thinking of a number between 1 and 10.
Can you guess it?
Enter your guess: 9
You entered: 9
Sorry, that is not correct.
Rerun and try again.
The error message should appear for any number other than the correct guess.
- One problem with our program is that a user may enter numbers outside the range of 1 through 10. We can test for this condition with one or more
if statements. Add this code to your program after the input statement and before the other if statements:
if (guess < 1) {
cout << "Error: guess must be >= 1\n";
return 1;
}
Checking user input is a common use of if statements. This type of code is known as input validation or input verification.
- Compile and run your program again and verify the output looks like:
I'm thinking of a number between 1 and 10.
Can you guess it?
Enter your guess: 0
You entered: 0
Error: guess must be >= 1
The error message should appear for any number that is less than one.
- 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.
- Compile your program and run it several times to see what message you get when you enter each of the following as a guess:
0
7
9
- 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
- Submit your program source code 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.
^ top
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 <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
if (guess != 7) {
if (guess < 7) {
cout << "Your guess is too low.\n";
} else {
cout << "Your guess is too high.\n";
}
} else {
cout << "*** Correct! ***\n";
}
return 0;
}
|
Nesting in the else Clause
Example Showing a Nested else if Statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
return 0;
}
|
Programming Style: Indentation of if-else-if Statements
- Note the alignment of the nested statements below:
if (guess < 7) {
cout << "Your guess is too low.\n";
} else {
if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
}
- The above style is WRONG
- Instead, we use:
if (guess < 7) {
cout << "Your guess is too low.\n";
} else if (guess > 7) {
cout << "Your guess is too high.\n";
} else {
cout << "*** Correct! ***\n";
}
- This shows more clearly that we are making a single choice among multiple alternatives
- Also, it prevents indentations from cascading to the right as we add more selections
^ top
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
As time permits, be prepared to answer these questions. You can find more information by following the links after the question.
- What is meant by the term "flow of control"? (3.3.1)
- What is the default flow-of-control operation after a statement finishes executing? (3.3.1)
- What part of an
if statement is indented? (3.3.2)
- 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;
}
- What is wrong with each of the following
if statements after executing the code: (3.3.2)
int guess;
cout << "Enter your guess: ";
cin >> guess;
if (7 == guess) then cout << "You guessed 7!\n";
if (guess = 7) cout << "You guessed 7!\n";
if ("7" == guess) cout << "You guessed 7!\n";
- Does the syntax for an
else clause include a test condition? (3.3.3)
- What is a relational expression and why are they used? (3.3.4)
- What is the output of the following code fragment? Why? (see textbook pg. 93)
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;
}
- For the above example code fragment, what is a better test condition than
(r * r == 2)?
- Of the following pairs of strings, which comes first in lexicographic order? (3.3.5)
"Harry", "Potter"
"Harry", "Hairy"
"car", "C++"
"car", "Car"
"car model", "carburetor"
- True or false? You can nest
if statements in either the if clause, the else clause, or both. (3.3.6)
- If you have a series of test conditions, and only one can be correct, what is the sequence of
if and else statement you should follow? (3.3.6)
^ top
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
|
^ top
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
^ top
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
- More information: Pair Programming for Homework Assignments
Why Pair Program?
- Students who pair program report:
- Higher confidence in a program solution
- More satisfaction with programming
- Instructors report higher completion and passing rates
Video Explaining Pair Programming
More Information
^ top
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
Getting Along
More Information
^ top
3.4.4: Summary
- Programming is about solving problems using a computer program
- Generally, you should develop programs in two phases:
- Problem-solving phase: the output is a working algorithm
- 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
Answer these questions to check your understanding. You can find more information by following the links after the question.
- What are three problems with solo programming? (3.4.1)
- What are the rules of pair programming? (3.4.2)
- Why should you change who is driving when you pair-program? (3.4.2)
- What are the jobs of the navigator? (3.4.2)
- How do you make sure that both people learn the material when pair programming? (3.4.2)
- 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)
- What is the key factor for success in using pair programming? (3.4.3)
^ top
Exercise 3.4
In this exercise we see who might be a compatible pair-programming partner for the next homework assignment.
Specifications
- We will count off and divide into separate groups
- Within your group, exchange names and email addresses, and then write down everyone's information.
- Next to each name, write the amount of programming knowledge and experience for that student using the following scale:
- Absolute beginner
- Some programming knowledge
- Can program in another programming language
- Can program in C++
- 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.
- Submit the
students.txt file to Blackboard as part of assignment 3.
^ top
Wrap Up
Due Next: A2-Implementing an Algorithm (2/25/10)
A3-Three Easy Programs (3/4/10)
- When class is over, please shut down your computer
- You may complete unfinished exercises at the end of the class or at any time before the next class.
^ top
Home
| Blackboard
| Day Schedule
| Eve Schedule
Syllabus
| Help
| FAQ's
| HowTo's
| Links
Last Updated: February 21 2010 @22:24:24
|