Welcome to Lesson 8! Learning Objectives By the end of today's class, you should know...
Announcements
Review Activity With a partner, answer the following questions:
string info = "Dogs are the best!!"; cout << info.length() << " " << info.substr(1, 3) << " " << info.substr(14, 5) << endl;
int age; cout << "Enter your age: "; cin >> age; if (age = 18) { cout << "First time voter!";Using |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| #include <iostream>
using namespace std;
int main() {
int guess = 0;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n\n"
<< "Enter your guess: ";
cin >> guess;
if (7 == guess) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
cout << "Try again.\n";
}
return 0;
}
|
Formatting the if
Statement
- It is important to format the
if
statement professionallyif (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
andelse
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
andif-else
statements - In practice, you should use the style dictated by your group's policy
- Or your professor's instructions
Activity 8.1: Guessing Game (10 pts)
- Find a partner for pair programming
- Open CodeBlocks and create a new C++ file.
- Add a block comment with your names and section information at the top.
- Copy the code below into your file and save it as selection.cpp. 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: - 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 anif-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 - 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 otherif
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.
- Upload your activity to Catalyst when you are finished. Both partners need to submit for full credit.
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":
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<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;
}
|
Activity 8.2: Let's Alphabetize! (10 pts)
- Open up CodeBlocks and create a new C++ file called alphabetize.cpp.
- Our program will take in two string inputs from the user, compare then and the output the two strings in alphabetical order.
- At the top of your program, declare a string variables called word1.
- Now declare a second string variable called word2.
- Next, write a cout statement welcoming your user to the program and letting them know that this program will alphabetize two words.
- Run your program to make sure it is giving you the output you expected.
- Let's prompt the user for the first word and store the result as word1.
cin >> word1;
- Do the same for the second word.
- Now, let's create an if-else statement to determine the ordering of the two words. And, then output the result to our user. The if-else statement will need to use string comparison as discussed above.
- The code that you have written could be a useful part of a larger program.
- Both partners should submit to Catalyst when finished.
Making Decisions Continued
"Nesting" if Statements
- The inner
if
statement is evaluated only if the test condition of the outerif
test first evaluates totrue
- 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
- You can also nest
if
statements in theelse
clause - When used this way, the computer can make 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 <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
Multiple Alternatives
- By using collections of if-else statements, a program can distinguish between multiple alternatives
Choosing Between Alternatives
- This program has five alternatives to choose from:
- "penny"
- "nickel"
- "dime"
- "quarter"
- erroneous input
- Note that the order that the alternatives are checked is unimportant
- We can follow the alternatives in the flowchart shown below
Flowchart of Multiple Alternative for Converting Coins to Values
- For example, consider the following example where a user enters the name of a coin, and the program displays the value:
Program Converting Coin Names to Values
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream> using namespace std; int main() { cout << "Enter coin name: "; string name; cin >> name; double value = 0; if (name == "penny") { value = 0.01; } else if (name == "nickel") { value = 0.05; } else if (name == "dime") { value = 0.10; } else if (name == "quarter") { value = 0.25; } else { cout << name << " is not a valid coin name\n"; } cout << "Value = " << value << "\n"; return 0; }
Activity 8.3: Grades (10 pts)
We want to write a program to calculate a student's letter grade according to the following table:
Numerical Grade Letter Grade greater than or equal to 90 A less than 90 but greater than or equal to 80 B less than 80 but greater than or equal to 70 C less than 70 but greater than or equal to 60 D less than 60 F
- Find a partner for pair programming.
- Copy the following program into a text editor, save it as grader.cpp. Change the comments, then compile and run the starter program to make sure you copied it correctly.
/*
* Name 1
* Name 2
* Section
*/
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
- Add code to get user input into a variable named
score
of typedouble
. When you run the program after adding this code, the output should look like:Enter a score: 95.7
Make sure you declare the variable with a compatible data type. Note that the underlined numbers above shows what theuser enters and is not part of your code.
- First we will look at a series of
if
statements and see thatif
statements alone are not enough to solve this problem. Copy the following into your program after the input statements:Compile and run your modified program. There is a logic problem with this code. Each test condition needs to work over a range of values rather than with a single value.
- One way to correct the problem is to nest an
if
statement inside of anotherif
statement. To see how this works, modify your code to add nestedif
statements as shown below:To test the range, the outer
if
statement tests the lower condition and the innerif
statement tests the upper condition.
{
{
{
{
{
- What is another way to fix this problem that we have already seen?
- Perhaps the most elegant solution is to nest an
if
statement in theelse
clause of the precedingif
. Modify the series ofif
statements to include anelse
clause as shown below:
{
{
{
}
- We are nesting
if
statements in theelse
clause. Nesting in theelse
clause makes each test condition of theif
statement exclusive of the others because each test condition eliminates all the preceding conditions.
- Compile and run your modified program to make sure you made the changes correctly. When you run the program, the output should look like:
Enter a score: 80 B
Run your program a few times with different score to verify that any score displays the correct letter grade.
- When finished, upload your program to Catalyst.
With a partner, correct the mistakes below
string pet = dog;
if (pet = “cat”) {
cout << “Meow!”;
} else (pet = “dog”) {
cout << “Definitely not a cat!”;
}
b.
char = a;
With a partner, answer the following question:
- What will the following print out to the console?
int num_puppies = 6;
if (num_puppies < 5) {
cout << "Woof!" << endl;
} else {
cout << "Bark!" << endl;
}
cout << "Arf!";
- Find a partner and answer the questions from today's learning objectives
- Assignment 8 due Tuesday
- Midterm 1 next class
- Lab 5 due Friday at midnight