What We Will Cover
Continuations
The expression (int) (a + b) is an example of
- an illegal expression
- a data type
- a declaration
- a cast
Homework Questions?
Homework Discussion Questions (Thursday)
- How do you make the jacket size adjustment take place every 10 years?
- How is an
if statement useful when testing for the age?
- Did anyone write the program without an if statement?
^ top
5.1: Counting Applications
Objectives
At the end of the lesson the student will be able to:
- Design and implement counting loops
- Design and implement loops that accumulate values
- Translate these designs into C++ code
|
^ top
5.1.1: Using Loops to Count
- Assume that we are given the task of writing a loop that prints the numbers from 1 to 5
- Thus, the program will display something like:
1
2
3
4
5
Since we understand our problem, our next step is to write our algorithm
When designing a loop, you need to consider three things:
- Loop body -- what statements are repeated each time through the loop
- Loop termination condition -- how to stop looping
- Initialization code -- get started correctly
We start with the first task and design our loop body
We decide to use a variable named count and to increment the count each time the loop repeats
print out the count
increment the count
Now we need to design how we stop looping (exit the loop)
We need a test condition for ending our loop when the count reaches 5
Working through our loop manually when the count is near 5, we see that our condition should be:
while count < 6
Now we move to the last task and ask ourselves what value the count variable must start with to print the first number correctly
We realize that we need to start the count variable at 1 to get the first number correct
set count = 1
Putting the pieces together we have:
set count = 1
while count < 6
print out the count
increment the count
We test this manually and then translate it into C++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream>
using namespace std;
int main() {
int count = 1; // initialization code
while (count < 6) { //loop termination condition
//loop body
cout << count << endl;
count = count + 1; // adjust the counter
}
return 0;
}
|
^ top
5.1.2: Making Bar Graphs
- Lets use our counting loop to make a horizontal bar graph
- Our task is:
Write a program that asks a user for a number and then displays a horizontal bar graph using '*' characters. Use one '*' for each number.
- For example:
Enter a number and I will display a bar graph.
Enter your number: 5
Your graph:
*****
Since we understand our problem, our next step is to write our algorithm
We start with getting the user input
Prompt the user
Get the number to graph
Now we need an algorithm to display the bar graph
Since we need to repeat something, we realize that we need to use a loop
Also, in a flash of inspiration, we realize that this problem is like our counting loop
We start our loop design by following the 3 steps:
- Loop body -- what statements are repeated each time through the loop
- Loop termination condition -- how to stop looping
- Initialization code -- get started correctly
First we decide what needs to be repeated during the loop
print out a '*'
increment the count
For the next step, we look at our loop and choose the terminating condition
while count < number enter by the user
Finally we choose a value to start the count
set count = 0
Putting all the pieces together we have:
Prompt the user
Get the number of stars to graph
set count = 0
while count < number of stars
print out a '*'
increment the count
We test this manually with a small number like 3 and then translate it into C++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = 0;
cout << "Enter a number and I will show its"
<< " bar graph.\nEnter your number: ";
cin >> number;
cout << "\nBar graph:\n";
int count = 0;
while (count < number) {
cout << '*';
count = count + 1;
}
cout << endl;
return 0;
}
|
^ top
5.1.3: Accumulating Values
- One common looping task is to input a list of numbers and calculate their sum
- For example, given the task:
Display the sum of the numbers from 1 through n, where n can be any positive number greater than 0.
- We start analyzing the problem working out a problem manually:
sum = 1 + 2 + 3 + 4 + 5 = 15
As we look at the problem, we notice that the difference from one number to the next is just 1
In a flash of inspiration, we realize that this problem is like our counting loop
We need to count the numbers from 1 to 5
However, instead of printing the numbers, we need to add them to some variable
Since we understand our problem, our next step is to write our algorithm
We start our loop design by following the design 3 steps:
- Loop body -- what statements are repeated each time through the loop
- Loop termination condition -- how to stop looping
- Initialization code -- get started correctly
First we decide what needs to be repeated during the loop
sum = sum + count
increment the count
Next we look at our loop and choose the terminating condition
while count <= number
For the third step, we initialize both the variables used in the loop
set sum = 0
set count = 1
Putting all the pieces together we have:
set sum = 0
set number = 0;
set count = 1
while count <= number
sum = sum + count
increment the count
We test this manually and find we forgot to display the sum after the loop
Display the sum after the loop
We add the missing step and then translate the algorithm into C++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <iostream>
using namespace std;
int main() {
int sum = 0, number = 0;
int count = 1;
cout << "Enter the number to sum to: ";
cin >> number;
while (count <= number) {
sum = sum + count;
count = count + 1;
}
cout << "Total sum = " << sum << endl;
return 0;
}
|
- Testing the code we find the answer matches our manual calculations
Calculating Products
^ top
5.1.4: Running Totals
- Let us look at how to accumulate a list of numbers
- For example, given the task:
Display the sum of the numbers entered by a user. Display this sum after every number is entered. When the user enters a 0, show the total and exit the program.
- We realize that this task is like our previous problem except that:
- We have to display the sum after every number is entered
- We do not know how many number the user will enter
- We need to exit after the user enters a 0
- The first change is easy -- we know how to print numbers!
- For the second and third changes, the specification gives us a hint
- We exit the loop when the user enters the number
0
- This is known as a sentinel-controlled loop
- The sentinel is the value that tells us when to exit the loop
- In this case, the sentinel value is the number 0
- Since we understand our problem, our next step is to write our algorithm
- We start our loop design by following the design 3 steps:
- Loop body -- what statements are repeated each time through the loop
- Loop termination condition -- how to stop looping
- Initialization code -- get started correctly
- First we decide what needs to be repeated during the loop
Prompt the user
Get the input
sum = sum + input
Next we look at our loop and choose the terminating condition
while number != 0
For the third step, we initialize the variables used in the loop
set sum = 0
set input = 0
We also need to display the sum after the loop terminates
Display the ending sum
Putting all the pieces together we have:
set sum = 0
set input = 0
while number != 0
Prompt the user
Get the input
sum = sum + input
Display the ending sum after the loop
We test this manually and find a problem!
- Since number is initialized to 0, the program never enters the loop
We fix the problem, retest and translate the algorithm to C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include <iostream>
using namespace std;
int main() {
double input = 1;
double sum = 0;
cout << "I will add up numbers for you\n\n";
while (input != 0) {
cout << "So far, sum = " << sum << endl;
cout << "Enter a number or 0 to exit: ";
cin >> input;
sum = sum + input;
}
cout << "Ending sum: " << sum << endl;
return 0;
}
|
Averaging the Tally
- An average is calculated by summing a quantity of numbers and then dividing by the count
- What would we add to the code to display the average of the numbers that were entered?
- How could we keep track of the highest number entered? lowest number?
^ top
5.1.5: Common Loop Pitfalls
Infinite Loops
- Common error: unintentional infinite loop
- For example, what is wrong with the following code?
1
2
3
4
5
6
7
8
9
10
|
#include <iostream>
using namespace std;
int main() {
int count = 0;
while (count < 5) {
cout << count << endl; // trace
}
return 0;
}
|
Empty Statements
- Remember that statements are terminated by a semicolon
- Is the following a legal statement?
;
Known as an empty or null statement
Empty statements are a common source of infinite loops
For example, what is wrong with the following code?
1
2
3
4
5
6
7
8
9
10
11
|
#include <iostream>
using namespace std;
int main() {
int count = 0;
while (count < 5); {
cout << count << endl; // trace
count++;
}
return 0;
}
|
Off-By-One Errors
- A common looping problem is the off-by-one error
- Often a less-than is confused with a less-than-or-equal-to
- For example, to sum the numbers from 1 to 5, what is wrong with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int count = 0;
while (count < 5) {
sum += count;
count++;
}
cout << sum << endl;
return 0;
}
|
Tracing Variables
- One good way to discover loop errors is to display the variables that change in the loop
- Tracing variables means watching their values change as the program executes
- You can insert temporary output statements in your program
cout << "count=" << count << ", sum=" << sum << endl;
For instance, we had trace statements in the infinite loop examples above
^ top
5.1.6: Summary
- One common use for loops is to count numbers
- We saw several applications for loops that count in this section
- Counting loops
- Making bar graphs
- Summing numbers
- We also used accumulation loops in this section to sum, or find the product of, a list of numbers
- Once you understand a programming problem that needs a loop, you design the loop in 3 steps
- Loop body -- what statements are repeated each time through the loop
- Loop termination condition -- how to stop looping
- Initialization code -- get started correctly
- Several problems that can occur when using a loop
- Infinite loops: loops that "never" end
- Off-by-one errors: starting or stopping at a wrong value
- Tracing variables is a good way to discover loopy errors
Check Yourself
- What are the parts of any loop?
- How do you code a counting loop?
- How do you code a loop to display horizontal bar graphs?
- How do you code a loop to accumulate values?
- How do you code a loop to keep a running total of numbers entered by a user?
- What are some common looping errors and how can you recognize them?
^ top
Exercise 5.1
Background
Recall that a char data type is stored by the computer as a number using the ASCII code (ASCII Table). Since a char is stored as an int by the computer, C++ lets you cast an int to a char.
Specifications
- Save the following code as
ascii.cpp
- Modify the code to list an integer and its ASCII character equivalent for the numbers 1 through 255.
- Use the format shown in the following excerpt:
65: A
66: B
67: C
- Submit your program source code along with your other exercises for this lesson.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream>
using namespace std;
int main() {
int count = 1; // initialization code
while (count < 6) { //loop termination condition
//loop body
cout << count << endl;
count = count + 1; // adjust the counter
}
return 0;
}
|
One possible answer.
^ top
5.2: More Control Statements
Objectives
At the end of the lesson the student will be able to:
- Use
switch statements for branching
- Use
do-while statements to control loops
- Use
for statements to control loops
- Use
break and continue statements with loops
|
- In this section, we learn about the rest of C++'s control statements
- These statements do not add new capabilities
- Just provide alternate ways of performing some tasks
- Since C++ code has them, you need to know how to use them
^ top
5.2.1: switch Statements
- The
switch statement provides an alternative to an if-else chain
- Executes a section of code depending on value of a variable
- General form:
switch (integerExpression) {
case label1:
statements
break;
case label2:
statements
break;
...
case labeln:
statements
break;
default:
statements
}
Keyword switch identifies the start of the switch statement
Expression in parenthesis is evaluated for comparison to each case label
integerExpression must evaluate to an integer
- Otherwise a compilation error occurs
Within a switch statement, keyword case labels each entry point into the code
- Code executes if
integerExpression matches the case label value
- Execution starts with the statement immediately following the match
Any number of case labels can be placed in any order
Any value that does not match starts executing with the statement after default
Execution continues until the end of the switch statement or a break statement
The break statement causes an immediate exit from the switch statement
Just as case identifies possible starting points, break determines end points
For Example:
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 <iostream>
using namespace std;
int main() {
int shippingOption = 0;
cout << "Enter a shipping option (1-3): ";
cin >> shippingOption;
switch (shippingOption - 1) {
case 0:
cout << "Parcel post delivery in two weeks.\n";
break;
case 1:
cout << "UPS delivery in three days.\n";
break;
case 2:
cout << "Fed-Ex overnight delivery.\n";
break;
default:
cout << "It may never get there!\n";
}
cout << "Ship it!\n";
return 0;
}
|
- Notice that each
case other than the last contains a break statement
- Ensures that the
switch statement is exited after a matching case is found
When to Use switch Statements
- You can only use switch statements with integer expressions
- Inherently less useful than
if-else statements
- Syntax is no clearer than
if-else statements
- Thus, no real need to ever use a switch statement
^ top
5.2.2: Conditional (Ternary) Operators
- Provides a compact
if-else structure
- Syntax:
operand1 ? operand2 : operand3;
First operand must be a conditional expression that evaluates to true or false
If operand1 is true, return operand2; otherwise return operand3.
For Example
- Following is an if-else statement
string outMessage;
int celsius;
cout << "Enter the Celsius temperature: ";
cin >> celsius;
if (celsius >= 100) {
outMessage = "Boiling!";
} else {
outMessage = "Not boiling";
}
cout << outMessage << endl;
Equivalent using the conditional operator
string outMessage;
int celsius;
cout << "Enter the Celsius temperature: ";
cin >> celsius;
outMessage = (celsius >= 100)
? "Boiling!"
: "Not boiling";
cout << outMessage << endl;
When to Use Conditional (Ternary) Operators
- Rarely used in professional programing
- Almost always clearer to use
if-else statements
^ top
5.2.3: do-while Statements
- Variation of the
while loop
- Syntax:
//Initialization
...
do {
//loop body
...
} while (loopTest); //loop condition
Initialization code may precede loop body
Loop test is after the loop body
Loop must execute at least once (minimum of at least one iteration)
Use when you want to force a minimum of one iteration
Validity Checks
- You can use
do-while statements to filter user input
- For example, assume we need a positive value from the user:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include <iostream>
using namespace std;
int main() {
//Loop initialization
double input = 0.0;
do {
//loop body
cout << "Enter a positive number: ";
cin >> input;
if (input < 0.0) {
cout << "You must enter a positive number!\n";
}
} while (input < 0.0); //loop condition
cout << "You entered: " << input << endl;
return 0;
}
|
When to Use do-while Statements
- Sometimes used in professional programming
- You can accomplish the same control flow with a
while loop
- You can use it whenever you want to force a minimum of one iteration
^ top
5.2.4: for Statements
- Provides a more compact loop
- Syntax:
for (initialization; condition; increment) {
// statements to repeat
}
initialization: a statement that defines the initial conditions of the loop
condition: an expression that determines when to continue (or end) the loop
increment: a statement evaluated at the end of each loop iteration
The statements to repeat are enclosed in the curly brackets
Execution Sequence
- When
for loop is reached, execute the initialization statement
- Check if
condition is true
- if
true then continue with Step 3
- Otherwise, continue with Step 6
- Execute the block containing the statements to repeat (loop body)
- When end of loop body is reached, execute the
increment statement
- Return to Step 2
- Loop is finished: continue with statements after the loop
Counter-Controlled-Loop Example
1
2
3
4
5
6
7
8
9
10
11
|
#include <iostream>
using namespace std;
int main() {
int count;
for (count = 0; count < 5; count++) {
cout << count << endl;
}
return 0;
}
|
- Note that code is indented in the loop body for readability
Counting Down
- Can also count downwards
- Positive numbers step higher (+inf) and negative numbers step lower (-inf)
- What is displayed with the following?
1
2
3
4
5
6
7
8
9
10
11
|
#include <iostream>
using namespace std;
int main() {
int count;
for (count = 5; count > 0 ; count--) {
cout << count << endl;
}
return 0;
}
|
When to Use for Statements
- Very often used in professional programming
- Especially useful for counter-controlled loops
^ top
5.2.5: break and continue Statements
- We saw the use of the
break statement in the switch statement
- However, you can use the break statement anywhere in your code
- The purpose of the
break statement is to terminate any program loop or conditional statement
- The
continue statement is similar except that instead of exiting a loop, it jumps to the end of the loop
- The causes the loop to skip the rest of the current iteration and start the next iteration
- The following code shows an example of break and continue
Example Using the break and continue Statements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include <iostream>
using namespace std;
int main() {
int count = 0;
while (true) {
count++;
if (count == 3) {
continue;
}
cout << count << endl;
if (count >= 5) {
break;
}
}
cout << "After count= " << count << endl;
}
|
When to Use break and continue Statements
- Use
break statements in switch statements only
- Never use
break in looping constructs
- Poor coding habit
- Loops and conditionals should only have one exit point
- You do not need to use
continue statements either
- You can accomplish the same operation other ways
^ top
5.2.6: Summary
- C++ provides many control statements
- They provide alternatives to the basic statements covered earlier
- Of those covered today, the most useful is the
for loop
- Provides a compact looping structure often used for counter-controlled repetition
- Includes three of the loop requirements in the syntax of the loop
Check Yourself
- What is the difference between a
while and a do-while loop?
- What are the advantages of using a
for loop compared to other looping statements?
^ top
Exercise 5.2
In this exercise we explore the similarities and differences between a for loop and a while loop.
Specifications
- Save the following code as
for5.cpp
- Convert the code to use a
for loop rather than a while loop.
- Turn in the modified source code as the answer to this exercise.
- Consider the following questions and be prepared to answer them:
Q1: What is the chief advantage of using a for loop?
Q2: Does the for or while loop seem best for counting loops? Why?
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream>
using namespace std;
int main() {
int count = 1; // initialization code
while (count < 6) { //loop termination condition
//loop body
cout << count << endl;
count = count + 1; // adjust the counter
}
return 0;
}
|
^ top
5.3: Predefined Functions
Objectives
At the end of the lesson the student will be able to:
- Create code that calls predefined functions
- Describe the flow of control of a function call
- Write code that generates random numbers
|
^ top
5.3.1: About Functions
Function -- a subprogram (method, procedure or subroutine) that executes a block of code when called.
- Programs can call functions at need, allowing repeated use of the function
- Function are often collected into libraries so they can be reused by many different programs
- C++ comes with many common libraries such as
<cmath> which contains functions like those shown in the table below
- Libraries must be "included" in a program
#include <cmath>
Newer standard libraries, such as cmath, also require the directive
using namespace std;
Library Functions in <cmath>
| Name |
Description |
Example |
Result |
| abs |
absolute value |
abs(-3.9)
abs(3.9) |
3.9
3.9 |
| exp |
exponent |
exp(1.0) |
2.71828 |
| log |
natural log |
log(10.0) |
2.30259 |
| pow |
powers |
pow(2.0, 3.0) |
8.0 |
| sqrt |
square root |
sqrt(4.0) |
2.0 |
^ top
5.3.2: Calling Functions
- Calling a function is like a boss asking a worker to do something
- In programming, the "boss" function asks a "worker" function to complete a task
- To ask a function to do something, the "boss" function uses a function call
- A function call consists of the function name and any parameters the function may need to do its task
- For example, to calculate the square root of a number, you would call the
sqrt() function:
sqrt(9.0);
When called with an argument of 9.0, the function returns a value of 3.0
Here are some more examples of function calls:
double result = pow(2.0, 3); // result is 8.0
cout << result << endl;
double num = -2.0;
double value = abs(num); // value gets 2.0
cout << value << endl;
^ top
5.3.3: Flow of Control for a Function Call
- To use functions well, you must understand their flow of control
- Consider the function call in the example shown below
1
2
3
4
5
6
7
8
9
10
|
#include <cmath>
#include <iostream>
using namespace std;
int main() {
double result = 1 + sqrt(9.0);
cout << result << endl;
return 0;
}
|
- The program starts executing in the
main() function
- The next line is an assignment statement, so the right-hand side is evaluated first
1 + sqrt(9.0)
The program evaluates the function call first since it has higher precedence than addition
When making the function call, the computer stops working on the current code and instead works on the code inside the function
The computer sends the information inside the parenthesis of the function call to the function
The function uses the data it was passed to perform its calculations
When the function is done, it returns the result of its calculation back to the code that called the function
The computer then uses the returned value to complete the computation
When the right-hand side is done, the value of the computation is saved in the variable on the left-hand side
^ top
5.3.4: Generating Random Numbers
- As an example of function calls, let us look at random numbers
- Random numbers are a series of numbers whose order cannot be predicted
- Many computational problems need to use random numbers
- Hard to find truly random numbers, even in real life
- Dice never perfect
- Cards never shuffled completely randomly
- Computers can only handle numbers within a finite range and limited precision
- The best that can be done in most cases is to generate pseudorandom numbers
- Sufficiently random for the task at hand
- rand() is a library function that produces series of psuedorandom numbers
- Range is
0 up to and including RAND_MAX
- Returns an "random"
int value
- For example:
cout << rand() << endl;
Initializing the Random Number Sequence
- If your program prints a random number, you will notice that it prints the same number every time the program runs
- To make the random numbers more random, you need to "seed" the random number generator
- For this you use the srand() function
- For instance:
srand(time(0));
The expression time(0) returns the number of seconds since January 1, 1970
The srand() function tells the computer to start with another number in the sequence
Since the time changes every time we run our program, the sequence of random numbers changes as well
^ top
5.3.5: Example Use of Random Numbers: Dice Simulation
- Let us use random numbers to simulate die rolling
- We need a number between 1 and 6, but
rand() returns a number between 0 and RAND_MAX
- We need only random numbers for a die and so we scale the range of
RAND_MAX using the % operator
- Now we can generate random integer numbers between 0 and 5
- To get a number between 1 and 6, we shift the numbers by adding 1
- Our code to simulate a single die with random numbers is now:
int die = 1 + rand() % 6;
cout << die << endl;
We can generalize our formula for producing integer random numbers to:
SHIFTING_VALUE + rand() % SCALING_FACTOR;
Let us use our code to simulate rolling a pair of dice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
srand(time(0));
int die1 = 1 + rand() % 6;
int die2 = 1 + rand() % 6;
cout << "You rolled a " << die1
<< " and a " << die2 << endl;
return 0;
}
|
- Note how the program simulates rolling 2 dice using 1 die at a time
- You would get a different result if you just generated a random number between 2 and 12
- What would you change to roll the two dice 10 times?
^ top
5.3.6: Summary
- A function is a block of code get executed when called
- C++ has many predefined functions in several libraries
- Libraries must be "included" in a program
#include <cmath>
Newer standard libraries, such as cmath, also require the directive
using namespace std;
One of the library functions generate "random" numbers: rand()
To seed the random number generator, you use the srand() function
We can use these functions to simulate the rolling of a die
srand(time(0));
int die = 1 + rand() % 6;
cout << die << endl;
Check Yourself
- What is a function?
- How do you call a function?
- What is a random number?
- How do you code a random number that simulates rolling a die?
^ top
Exercise 5.3
In this exercise we look at the randomness of the rand() function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
srand(time(0));
int die1 = 1 + rand() % 6;
int die2 = 1 + rand() % 6;
cout << "You rolled a " << die1
<< " and a " << die2 << endl;
return 0;
}
|
Specifications
- Save the code as
dice.cpp
- Change the code to add a loop that rolls the two dice 10 times.
- Display the output of the roll each time through the loop.
- Submit your source code as the solution to this exercise
Example Output
You rolled a 1 and a 1
You rolled a 4 and a 5
You rolled a 5 and a 6
You rolled a 3 and a 6
You rolled a 2 and a 4
You rolled a 4 and a 6
You rolled a 3 and a 4
You rolled a 1 and a 5
You rolled a 4 and a 5
You rolled a 4 and a 6
^ top
Wrap Up
Reminders
Due Next: A4: Clothing Sizer (3/8/07)
Exercise 4 and CodeLab Lesson 4 (3/8/07)
A5: Tally Ho! (3/15/07)
Exercise 5 and CodeLab Lesson 5 (3/15/07)
- 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
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: March 08 2007 @16:37:22
|