Welcome to Lesson 9! Learning Objectives
By the end of today's class, you should know...
Announcements
Review ActivityWith a partner, identify 3 mistakes in the below code. Then, correct them:
string vehicle; cout << "Do you own a car or a truck?: "; cin >> vehicle; if (vehicle = car) { cout << "You drive a car!\n"; } else (vehicle = truck) { cout << "You drive a truck!\n"; }
Making Decisions Continued
|
Nesting in the else
Clause
- When nesting
if
statements in theelse
clause, 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 9.1: 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.
- Open a new project in Eclipse called Grader with a file named grader.cpp. Change the comments to include your name, your partner's name and your section info.
- 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 the user 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:string grade;
if (score >= 90)
{
grade = "A";
}
if (score >= 80)
{
grade = "B";
}
if (score >= 70)
{
grade = "C";
}
if (score >= 60)
{grade = "D";
}
if (score < 60)
{
grade = "F";
}cout << grade << endl;
Compile and run your 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.
- Perhaps the most elegant solution to this problem 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, both partners should upload the program to Canvas.
When Order Matters
- In some cases, the order of the tests is important
- For example, look at the following program from the textbook that displays a description of the likely impact of an earthquake based on its magnitude on the Richter scale
Program Showing Multiple Alternatives Where Order Matters
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
|
#include <iostream>
using namespace std;
int main() {
cout << "Enter a magnitude on the Richter scale: ";
double richter;
cin >> richter;
if (richter >= 8.0) {
cout << "Most structures fall\n";
} else if (richter >= 7.0) {
cout << "Many buildings destroyed\n";
} else if (richter >= 6.0) {
cout << "Many buildings considerably damaged, "
<< "some collapse\n";
} else if (richter >= 4.5) {
cout << "Damage to poorly constructed buildings\n";
} else if (richter >= 3.5) {
cout << "Felt by many people, no destruction\n";
} else if (richter >= 0) {
cout << "Generally not felt by people\n";
} else {
cout << "Negative numbers are not valid\n";
}
return 0;
}
|
Order Is Important
- Note that the order of the tests is important to ensure that the right results are printed
- If we rearranged the order of the
if-else
statements, we would get the wrong results - For example, if we reversed the order of the tests:
if (richter >= 0) { // tests in wrong order cout << "Generally not felt by people\n"; } else if (richter >= 3.5) { cout << "Felt by many people, no destruction\n"; } else if (richter >= 4.5) { cout << "Damage to poorly constructed buildings\n"; } else if (richter >= 6.0) { cout << "Many buildings considerably damaged, " << "some collapse\n"; } else if (richter >= 7.0) { cout << "Many buildings destroyed\n"; } else if (richter >= 8.0) { cout << "Most structures fall\n"; } else { cout << "Negative numbers are not valid\n"; }
- This does not work because all values meet the first condition
- Every other test will never be attempted
Importance of Using if-else-if
Structure
- Note that we cannot remove the
else
portion of the structure like shown below:if (richter >= 8.0) { // Does not use else cout << "Most structures fall\n"; } if (richter >= 7.0) { cout << "Many buildings destroyed\n"; } if (richter >= 6.0) { cout << "Many buildings considerably damaged, " << "some collapse\n"; } if (richter >= 4.5) { cout << "Damage to poorly constructed buildings\n"; } if (richter >= 3.5) { cout << "Felt by many people, no destruction\n"; } if (richter >= 0) { cout << "Generally not felt by people\n"; } if (richter < 0) { cout << "Negative numbers are not valid\n"; }
- The conditions must be exclusive and we need the else-if conditions to ensure exclusivity
- Independent
if
statements may cause a single input to print several messages
Numbers, Formatting and More About Operators
Decimal Formatting
- Sometimes programs may not display numbers as you would expect!
- Consider the following program and what it will display:
#include<iostream> using namespace std; int main() { double price = 78.50; cout << "The price is $" << price << endl; }
- We must explicitly tell C++ how to output numbers in our programs!
- These commands do not produce any output but change how
cout
outputs floating-point numbers - "Magic Formula" to force decimal places:
cout << fixed // fixed notation, not scientific << setprecision(2); // show 2 decimal places
- The commands
fixed
andsetprecision
are known as manipulators because you can manually change how cout works - You can put both commands on one line:
cout << fixed << setprecision(2);
- Also, you can combine the commands with other output:
cout << "The price is $" << fixed << setprecision(2) << price << endl;
- To use these commands, you must include the
iomanip
library:#include <iomanip>
- Once we set the decimal formatting, it stays set.
Constants and Magic Numbers
- A constant variable (or constant) is a variable that cannot change after being assigned a value
- Sounds oxymoronic, but is actually quite useful
- To declare a constant, we use the keyword:
const
const int MY_CONST = 1;
- Note that we must assign a value when the constant is declared
- Also note that the name is all uppercase letters with an underscore separator
- This is a common coding convention that you must follow
Magic Numbers
- Imagine that you are a programmer hired to modify a payroll program
- You come across the following section of code:
double pay; pay = hours * 7.5 + (hours / 40) * (hours - 40) * 7.5 * 0.5;
- The numbers are important to the program, but what do they mean?
- Numbers like these are called Magic Numbers.
- They are magic because the value or presence is unexplainable without more knowledge
- Often, no one knows what they mean after 3 months, including the author
- A programmer can often infer the meaning of numbers after reading the code carefully
- A much better coding style is to use named constants rather than literal numbers
- For example:
const double WAGE = 7.5; const double OVERTIME_ADDER = 0.5; const int HOURS_PER_WEEK = 40; double pay; pay = hours * WAGE + (hours / HOURS_PER_WEEK) * (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_ADDER;
- Now it is much easier to understand the code and see any problems or limitations in it
- Another reason to use named constants is that it is easier to change the value of the number
- In the above example, we can easily change the WAGE without making errors in other parts of our code
Programming Style: Constant Variables and Magic Numbers
- Since the meaning of literal (magic) numbers is hard to remember, we should declare constants instead:
const int FEET_PER_YARD = 3; const double PI = 3.14159265358979323846; const double WAGE = 7.5; const double OVERTIME_ADDER = 0.5; const int HOURS_PER_WEEK = 40;
- Note that the name is all uppercase letters with an underscore word-separator
- This is a common coding convention that you must follow for your constants
More Information
- No Magic Numbers: from "How To Document and Organize Your C++ Code"
- Magic number (programming): about magic numbers in code from Wikipedia
Assignment Operators
- As we discussed before, we assign values to variables using an equal (
=
) signint sum = 0;
- However, the equal sign is really an assignment operator and does not denote equality
- Thus, unlike math, we can have the same variable on both sides of an equals sign:
int sum = 25; // initialize sum to 25 sum = sum + 10; // add to sum
- Note that the value of the variable is changed in the second line
- Reading variables from memory does not change them
- Values placed into a variable replace (overwrite) previous values:
Shortcut Assignment Operators
- We can use additional operators to calculate values and assign them to the variable on the left all in one statement
- Known as shortcut assignment operators
- The general syntax is:
variable op= expression;
- Where op is one of the five arithmetic operators:
+
,-
,*
,/
,%
- For example, the following two statements create the same result:
x = x + 3; x += 3;
- Shown below are the assignment operators with examples of how they are used:
Summary of Assignment Operators
Operator | Description | Example | Equivalent To |
---|---|---|---|
= |
Assigns the value of the expression on the right to the variable on the left | x = 3 |
|
+= |
Adds the expression on the right to the variable on the left | x += 3 |
x = x + 3 |
-= |
Subtracts the expression on the right from the variable on the left | x -= 3 |
x = x - 3 |
*= |
Multiplies the expression on the right to the variable on the left and saves the result in the variable on the left | x *= 3 |
x = x * 3 |
/= |
Divides the variable on the left by the expression on the right and saves the result in the variable on the left | x /= 3 |
x = x / 3 |
%= |
Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the left | x %= 3 |
x = x % 3 |
Increment and Decrement Operators
- Adding or subtracting one is a common operation in programming
- C++ provides arithmetic shortcuts for these operations with the increment and decrement operators
- The increment operator (
++
) adds 1 to a variable's value - Pre-increment adds 1 before evaluating an expression
++sum;
- Post-increment evaluates the expression and then adds 1
sum++;
- The decrement operator works like the increments operator, except it subtracts 1 from the variable:
--sum sum--
- Pre- and post- increment matters when the operation is part of a larger expression
- For example, consider the code:
int x = 5; int y = x++; cout << "x=" << x << " y=" << y;
- We may expect y to be 6 after this code executes
- Instead, y has the value of 5
- The reason is that
++
after a variable (post-increment) is equivalent to:y = x; x = x + 1;
- On the other hand,
++
before a variable (pre-increment) is equivalent to:x = x + 1; y = x;
Casting
Cast: change the data type of the returned value of an expression
- Recall that different data types are stored in different forms
- Sometimes you need to change from one form to another
- For example: arithmetic adding a
double
and anint
value - C++ will automatically cast one value to another
- Known as implicit casting or type coercion
- Programmers can also explicitly cast data types
- Explicit casting changes the data type for a single use of the variable
- Precede the variable name with the new data type in parentheses:
(dataType) variableName
- The type is changed only for the single use of the value
- For example:
double x = 2.99999; x = (int) x; cout << x << endl;
- The value of
x
is converted from typedouble
toint
before assigning the converted value tox
- However,
x
remains a typedouble
and the cast only applies to a single use ofx
- The above example shows a common use of casting -- removing the decimal part of a floating-point number
- Note that the decimal portion of the number is truncated and NOT rounded
- Decimal part is lost (discarded, ignored, thrown away)
- Another use is to convert an
int
to adouble
when dividing two int numbers and a decimal result is desired - For example:
double x = (double) 9 / 5; cout << x << endl;
- Still another use is to prevent compiler warnings
- For example:
double x = 2.3; int n = x; cout << n << endl;
- The above may cause a compiler warning with the settings we use:
warning: converting to 'int' from 'double'
- To remove the warning, we use a cast:
double x = 2.3; int n = (int) x; cout << n << endl;
- This tells the compiler that you intended to convert from
double
toint
Example Application Using Casting:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
double input;
cout << "Enter hours: ";
cin >> input;
int hours = (int) input; // prevents warning
int minutes = (int) ((input - (int) input) * 60);
cout << "In hours and minutes, this is "
<< hours << ":" << minutes << endl;
return 0;
}
|
Integer Overflow
- An integer is stored in a computer as a pure binary number:
- The sign bit sets whether the number is positive (0) or negative (1)
- The other bits represent the value, in this case
123
- There are only a finite set of numbers in an integer value
- What happens when an integer is too big for its type?
int bigPlus = 2147483647; cout << "Big number: "; cout << bigPlus + 1 << endl; int bigMinus = -2147483647; cout << "Small number: "; cout << bigMinus - 2 << endl;
- The number "wraps around" from the highest number to the lowest
- You must be careful that your program will not go beyond the range of its data types
- Can't sleep: from xkcd
More Integer Types
- To increase the range, C++ has the
long
data type - Originally, the
long
data type was 32 bits while theint
was 16 bits - However, with the development of 32 bit computers, the
int
value was extended to 32 bits but thelong
was left at 32 bits - Thus, at the present time,
int
andlong
are the same size on most computers - In addition, C++ has
unsigned
integer types you can use to change the range - Rather than integer ranges from -2147483647 to 2147483647,
unsigned int
ranges from 0 to 4294967295 - New to C++11 (a newer version of C++) is the type long long which is a 64 bit type.
Floating-Point Precision and Range
- Floating-point numbers are not exact representations of real numbers
- Rounding errors occur in repeated calculations
- Type double has about twice the precision of type float
- However, even type double can have rounding errors
cout << setprecision(17); cout << .8F + .1F << endl; cout << .8 + .1 << endl;
- When floating point numbers get too large, they are set to
inf
- For instance:
cout << 2E38F + 2E38F << endl;
- Similarly, when numbers are too small they are set to
0.0
The Moral
- Integer and floating-point data types work well most of the time
- However, if we work with large positive or negative integers, we must be sure we do not exceed the range of the data type
- Also, floating-point numbers have limited precision
- When math operations are performed repeatedly, they can become less precise
- Thus we must be careful of precision when using floating-point numbers
Activity 9.2: Prices (10pts)
- Find a partner for pair programming.
- Open up Eclipse and create a new projected named Prices with a file called price.cpp. Copy and paste the below code into it beneath the comment with your and your partner's names.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream> #include <iomanip> using namespace std; int main() { string name; double price = 0; cout << "Enter the product name: "; cin >> name; cout << "Price of the " << name << ": "; cin >> price; // Insert new statements here cout << "Total price: $" << price << endl; return 0; }
- Compile and run the starter program to make sure you entered it correctly.
When you run the program, the output should look like this:
Enter the product name: iPod_Nano Price of the iPod_Nano: 149.50 Total price: $149.5
Note the format of the numbers output for the total price. We will address this formatting issue later in the exercise.
- Run the program again for a product with a very high cost, like a Boeing 777:
Enter the product name: Boeing__777 Price of the Boeing_777: 212345678 Total price: $2.12346e+08
Note the format of the numbers output for the total price. This format is called exponential notation. You may have encountered it in some of your math classes.
- Let us correct the formatting of the total price. Enter the following code before the statement that prints the total price:
cout << fixed // fixed notation, not scientific << setprecision(2); // show 2 decimal places
These statements are referred to as the "magic formula" because they for C++ to output statements in a "standard" format. Note what each statement accomplishes.
- Compile and run your program again and verify the output looks like:
Enter the product name: Boeing_777 Price of the Boeing__777: 212345678 Total price: $212345678.00
- Let us add a constant that we will
use later in our program. Enter the following code after the magic
formula and before the statement that prints the total price:
const int PERCENT = 100;
A constant variable (or constant) is a variable that cannot change after being assigned a value. Using a constant lets us avoid using a vague number.
- Now
we will add sales tax to the price of the product. Enter the following
code after the constant and before the statement that prints the total
price:
double taxRate = 0; cout << "Enter sales tax rate (%): "; cin >> taxRate; double tax = price * taxRate / PERCENT; price += tax;
Notice the last statement:
price += tax;
. This is an alternate way to code the statement:price = price + tax;
. - Compile and run your modified program and verify the output looks like:
Enter the product name: iPod_nano Price of the iPod_nano: 89.50 Enter sales tax rate (%): 9.5 Total price: $98.00
- Now we will find the whole dollars
and cents of the amount to demonstrate casting. Enter the following code
after the statement that prints the total price and before the return
statement:
int dollars = (int) price; cout << "In whole dollars: $" << dollars << endl;
Notice the
(int)
in the first statement. This is known as a type cast or just cast.
- Compile and run your modified program and verify the output looks like:
Enter the product name: iPod_nano Price of the iPod_nano: 89.50 Enter sales tax rate (%): 9.5 Total price: $98.00 In whole dollars: $98
Wrap Up
- Find a partner and answer the questions from today's learning objectives
- Assignment 9 due Tuesday at 9:20am on Canvas