What We Will Cover
Continuations
Homework Questions?
The expression (int) (a + b) is an example of
- an illegal expression
- a data type
- a declaration
- a cast
^ top
4.1: Making Selections
Objectives
At the end of the lesson the student will be able to:
- Formulate relational expressions to produce boolean values
- Generate selection statements
|
^ top
4.1.1: Flow of Control
- The term flow of control refers to the order in which a computer executes instructions
- All programs can be written with just three control-flow elements:
- Sequence - continue with the next instruction
- All programs continue with the next instruction by default
- To make the program do something else, you code either a selection or repetition (looping) statement
- Selection - a choice between at least two options
- Either execute some instruction based on a condition
- Or continue with the next instruction
if
if-else
- Repetition - a loop (repeat a block of code)
At the end of the loop:
- Either go back and repeat the block of code
- Or continue with the next instruction after the block
for
do-while
while
- We will first consider selection statements
^ top
4.1.2: The Value of a Relationship
- To make a selection or repetition statement, you need to code a test condition
- The computer uses the condition to decide whether or not to execute the statement
- One way to code a test condition is to use a relational expression
Relational Expressions
- In addition to arithmetical operations, all computers can compare numbers
- Many decisions can be reduced to choosing between two numbers
- Comparing numbers can make computers seem "intelligent"
- Expressions that compare numbers are called conditions or relational expressions
- Simple conditions have one relational operator comparing two values

- A condition always evaluates to either
true or false
- The relational operators are:
| Math |
Name |
C++ |
Example |
Result |
| = |
Equal to |
== |
5 == 10 2 == 2 |
false true |
| ≠ |
Not equal to |
!= |
5 != 10 2 != 2 |
true false |
| < |
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 |
| > |
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 |
- You may use relational operators with any numerical data
^ top
4.1.3: Using if Statements
- The simplest selection statement is an
if statement
- This statement executes a section of code only if a condition is true
- If the test condition is
false, the computer skips the code
if (condition) {
// execute statements only if true
}
For clarity:
- Write the
if on a different line than the executed block
- Indent statements that are executed if the condition evaluates to
true
For Example
- What is new about the following code?
- What is the test condition?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
int guess;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n";
cin >> guess;
if (guess == 7) {
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 block
- Curly braces are not always required, but the best practice is to always include them
^ top
4.1.4: Using if-else Statements
- Sometimes we want to choose between two actions
- If a condition is true
- Otherwise it is false
- General syntax:
if (condition) { // evaluates to true
// execute statements only if true
} else {
// execute statements only if false
}
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
For clarity, write the if and else on different lines than the other statements
Also, indent the other statements
For Example
- What do you notice that is different about the following 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 guess;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n";
cin >> guess;
if (guess == 7) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
}
return 0;
}
|
Programming Style: Placement of Braces
- Different groups have different practices for placing curly braces in
if and if-else statements
- In practice, you should use the style dictated by your group's policy
- Or your professor's instructions
- For the acceptable styles for this course see: Curly Braces
^ top
4.1.5: Summary
- Flow of control refers to the order in which a computer executes statements
- There are only three types of flow of control
- Sequence: continue with the next instruction
- Selection: a choice between at least two options
- Repetition: repeat a block of code (loop)
- To make a selection or repetition statement, you need to code a test condition
- The computer uses the condition to decide whether or not to execute the statement
- One way to code a test condition is to use a relational expression
- Relational operators include:
== != < <= > >=
Selection is a choice between at least two options
Selection statements include:
if
if-else
Check Yourself
- What is meant by the term "flow of control"?
- What is the default flow-of-control" operation after a statement finishes executing?
- What is the value of
x after the following code segment?
int x = 5;
if (x > 3) {
x = x - 2;
} else {
x = x + 2;
}
^ top
Exercise 4.1
Take 10 minutes to complete the following:
- Start a text file named exercise4.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 4.1
Specifications
For the values:
int a = 5, b = 2, c = 4, d = 6;
Record the in your exercise4.txt file which of the following conditions are true and which are false.
a > b
a != b
d % b == c % b
a * c != d * b
b % c * a != a * b
As a final part of this exercise, write a short program that asks the user for a test score. If the score is greater than or equal to 60 then print, "You passed!"; otherwise print, "Sorry, you failed"
Name this program testscore.cpp and submit it with the lesson 4 exercises. You may use the following code to get started.
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter your test score: ";
cin >> score;
// Insert statements here
return 0;
}
^ top
4.2: More About Selection
Objectives
At the end of the lesson the student will be able to:
- Construct test conditions that evaluate to a boolean value
- Use logical operators to assemble complex conditions
- Avoid some common pitfalls when creating test conditions
|
^ top
4.2.1: Test Conditions and Boolean Values
- All selection and loop statements have a test condition
- This test condition controls the operation of the statement
- You must construct test conditions so they always evaluate to a boolean value
Boolean Values
- Boolean types have just one of two values: either
true or false
bool truth = true, lies = false;
Recall that an expression is part of a statement that returns a value
Thus, a boolean expression is some code that returns either true or false
For example:
true
false
2 < 5
a == b
We use boolean expressions like these to control selection and looping statements
What is Truth?
- "What is truth?" may seem more appropriate for philosophy than programming
- However, in programming we need to know how the computer interprets truth
- C++ stores boolean values numerically:
true as 1 and false as 0
cout << true << endl;
cout << false << endl;
cout << boolalpha; // show output as true or false
cout << true << endl;
cout << false << endl;
^ top
4.2.2: Comparing Characters
- Character data can be evaluated using relational operators
- For these comparisons,
char values are automatically changed into int values
- These conversions are done using ASCII codes
- Letters nearer to the start of the alphabet have lower numerical values
- Thus a numerical comparison can decide the alphabetical order of characters
- For example:
cout << boolalpha; // show output as true or false
cout << ('A' < 'C') << endl;
cout << ('A' > 'C') << endl;
cout << ('A' <= 'Z') << endl;
cout << ('X' >= 'Y') << endl;
cout << ('X' == 'X') << endl;
cout << ('X' != 'X') << endl;
More Information
^ top
4.2.3: Nested if Statements
- Note that you can include
if statements within other if statements
- Each inner
if statement is evaluated only if the outer condition is met
For Example
- What do you notice that is different about the following code?
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() {
double temp = 0;
cout << "Enter a temperature: ";
cin >> temp;
if (temp > 65) {
if (temp > 75) {
cout << "That's too hot!\n";
} else {
cout << "That's just right.\n";
}
} else {
cout << "That's cold!\n";
}
return 0;
}
|
- Nesting
if statements inside of if statements can be confusing when too deep
- Rule of thumb: no more than three deep
Nesting in the else Clause
- You can also nest
if statements in the else clause
- Unlike nesting in the
if clause, you can next in else clauses as deep as you like
- For example, what do you notice that is different about the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include <iostream>
using namespace std;
int main() {
double temp = 0;
cout << "Enter a temperature: ";
cin >> temp;
if (temp > 75) { // first condition
cout << "That's too hot!\n";
} else if (temp > 65) { // next condition
cout << "That's just right.\n";
} else { // default condition
cout << "That's cold!\n";
}
return 0;
}
|
- Note the alignment of the nested statements
- Instead of:
if (temp > 75) { // first condition
cout << "That's too hot!\n";
} else {
if (temp > 65) { // next condition
cout << "That's just right.\n";
} else { // default condition
cout << "That's cold!\n";
}
}
We use:
if (temp > 75) { // first condition
cout << "That's too hot!\n";
} else if (temp > 65) { // next condition
cout << "That's just right.\n";
} else { // default condition
cout << "That's cold!\n";
}
This structure clearly shows the operation of the code
Also, it prevents indentations cascading to the right
^ top
4.2.4: Testing Multiple Conditions
- One reason to use nested
if statements is for testing multiple conditions
- However, a better way is to combine conditions using conditional operators
- Conditional operators allow you to consider multiple cases and to change conditions
AND Operation
- One such operator is "and", which is spelled
&& in C++
- For example, the following is true if
temp >= 65 and temp <= 75
(temp >= 65) && (temp <= 75)
When two boolean expressions are connected using && the whole expression is true only if both conditions are true
However, if either condition is false the whole expression is false
OR Operation
- Also, you can combine two boolean expressions using the "or" operator, spelled
|| in C++
- For example, the following is true if
temp < 65 or temp > 75
(temp < 65) || (temp > 75)
When two boolean expressions are connected using || the whole expression is true if either condition is true
Only if both conditions are false is the entire expression false
NOT Operation
- Additionally, you can negate any expression using
! operator
- To use it, place the entire expression in parenthesis and place the
! operator in front
- For example, to get a
temp between 65 and 75, we can negate our previous example:
!((temp < 65) || (temp > 75))
Parenthesis
- Remember that a boolean expression in an
if statement must be enclose in parenthesis
- Thus, an if statement that uses an
&& operator with two comparisons looks like:
if ((temp >= 65) && (temp <= 75)) {
Also note that relational operators have a higher precedence than logical operators
Thus, you can remove the inner parenthesis without affecting the meaning
if (temp >= 65 && temp <= 75) {
However, if using parenthesis is clearer to you then use the extra parenthesis
For Example
#include <iostream>
using namespace std;
int main() {
double temp = 0;
cout << "Enter a temperature: ";
cin >> temp;
if (temp >= 65 && temp <= 75) {
cout << "That's just right.\n";
} else {
cout << "That's uncomfortable!\n";
}
return 0;
}
^ top
4.2.5: Conditional Pitfalls
- Unfortunately, you can write many things in C++ that should be incorrect but end up working for some obscure reason
- This means that you can code something that should create an error message but does not
- Thus, a program may compile and run with no error messages but still be wrong
- Since you may not realize that it is wrong, it can be hard to find and correct these types of errors
Using = Instead of ==
- One common mistake is to use
= when you mean to use ==
- For example, look at the test condition in the following code:
if (guess = 7) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
}
Notice that the condition is really an assignment statement and not a test
You would think that it would fail to compile -- but it does not
However, it will not work as you might expect
Note that if you compile with all the options that I suggest, that the compiler will display a warning:
guess.cpp: In function `int main()':
guess.cpp:10: warning: suggest parentheses around
assignment used as truth value
Another way to prevent this type of problem is to reverse the order of your test condition
if (7 = guess) {
Now the compiler will give you an error message and your code will not compile
guess.cpp: In function `int main()':
guess.cpp:10: error: non-lvalue in assignment
However, if you correctly use == then your code will compile
if (7 == guess) {
Strings of Inequalities
- Do not use a string of inequalities like the following:
if (a < b < c) {
cout << "b is between a and c\n";
}
Your code will probably compile and run but give incorrect results
Instead, the correct way is to use && as follows:
if (a < b && b < c) {
cout << "b is between a and c\n";
}
Strings of Logical Operators
- Logical expressions often read like "normal" English.
- However, programming requires more detail
- For example, the following code will compile and run but give wrong results
if (guess == 7 || 8) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
}
Instead, the correct way is to use || as follows:
if (guess == 7 || guess == 8) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
}
^ top
4.2.6: Summary
- All selection and repetition statements have a test condition
- This test condition controls the operation of the statement
- You must construct test conditions so they always evaluate to a boolean value
- Boolean types have just one of two values: either
true or false
- A boolean expression is any expression that returns either
true or false
- You can compare letters as well as numbers since letters are stored as numbers
- Used to alphabetize letters and words in a computer program
- Nested
if statements are legal but often confusing
- Best to avoid nesting
if statements in the if clause
- In contrast, nesting
if statements in the else clause is fine
- When you need to compare several conditions, you use logical operators
! && ||
For example:
(temp >= 65) && (temp <= 75)
(temp < 65) || (temp > 75)
!((temp < 65) || (temp > 75))
Unfortunately, you can write things in C++ that should be incorrect but end up working for some obscure reason
These types of errors are often very difficult to find
One common mistake is to use = when you mean to use ==
if (guess = 7) {
Another problem is trying to use a string of inequalities without a logical operator separating each condition
if (a < b < c) {
Which should be written as:
if (a < b && b < c) {
Another error is trying to use logical operators without enough operand
if (guess == 7 || 8) {
Which should be written as:
if (guess == 7 || guess == 8) {
Check Yourself
- What two values can a boolean variable contain?
- Why can you compare character data using a relational expression?
- What is the effect of having an
if statement nested in an if statement?
- What is the effect of having an
if statement nested in an else statement?
- When does an AND (
&&) of two or more conditions evaluate to true?
- When does an OR (
||) of two or more conditions evaluate to false?
- What is the effect of the NOT (
!) operator?
^ top
Exercise 4.2
Specifications
A student's letter grade is calculated 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 |
- Save the following code as
grader.cpp
- Change the code to:
- Get a score from the users as an double number between 0 and 100
- Convert the score to a letter grade
- Display the letter grade
- Submit your program along with your other exercises for this lesson.
#include <iostream>
using namespace std;
int main() {
double score;
cout << "Enter a score: ";
cin >> score;
// Insert statements here
return 0;
}
^ top
4.3: Repetition (Loops)
Objectives
At the end of the lesson the student will be able to:
- Use
while statements to repeat sections of code
- Apply commonly-used looping patterns
- Avoid common looping problems
|
^ top
4.3.1: Introduction to Loops
- Loops are used to repeat sections of code
- General loop structure:
- Initialization code
- Loop termination condition
- Loop body
- C++ has 3 loop statement
while
do-while
for
However, you can use any loop statement and achieve the same result
Thus, I am only going to teach one loop statement at this time
Later on we will look at the other loop statements
^ top
4.3.2: Coding while Statements
- The
while loop is one of the simplest loop
- Use a
while loop to repeat a section of code
- The repetition continues as long as the test condition remains true
while loop Syntax:
//Initialization
...
while (condition) { //loop termination condition
//loop body
...
}
Initialization statements usually precede the while loop
Tests the (condition) at start of every loop iteration
- Continues as long as
condition evaluates to true
Note that if the loop condition is false at first then the loop body never executes
The loop body can be a single statement or a block
You can put any legal statement in the body of the loop
- Including
if statements and other loop statements
Diagram of while Loop Operation

^ top
4.3.3: Example Application: Play Again Program
- The following application simulates the play of an exciting game
- Note the 3 important parts of the loop
- Loop body -- statements to execute repeatedly
- Loop condition
- Loop initialization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
int main() {
char answer = 'y';
while (answer == 'y') {
cout << "\nPlaying an exciting game!\n";
cout << "Do you want to play again? (y/n) ";
cin >> answer;
}
cout << "\nThanks for playing!\n";
return 0;
}
|
- Which statement initializes the loop variables?
- Which part is the loop condition?
- Which part is the loop body?
- Loops of this type are often called the main programming loop
Formatting the Code
- It is important to format the loop code correctly
- Note how the repeated code is indented inside the loop
- This lets us know visually what code is repeated and which is not
- Also note the placement of curly braces
- Different groups have different practices for placing curly braces in a loop statement
- For the acceptable styles for this course see: Curly Braces
^ top
4.3.4: Understanding the Main Loop
- We can generalize the main loop of our example
- Implementation can be different from one program to another
- However, the basic structure is the same for most programs
Program Flow with a Main Loop
Notes on the Program Flow
- Set Up (statements before the loop)
- Declare and initialize variables
- Provide instructions
- Repeated steps (loop body)
- Get User Input
- Update Variables
- Update Display
- Program Done?
- Check if the program is completed
- Often the user decides to exit
- Change variables in the test condition of the loop
- Shut Down (statements after the loop)
- Provide the user any final information
- End the program
^ top
4.3.5: Summary
- Loops are used to repeat sections of code
- General loop structure:
- Initialization code
- Loop condition -- evaluated during the loop
- Loop body
- The
while loop is a simple repetition statement
- Syntax:
//Initialization
...
while (condition) { //loop termination condition
//loop body
...
}
Most programs have a main loop
Statements inside the loop repeat until the program exits
Check Yourself
- What are the three parts of any loop?
- How do you code a
while statement?
- What is the purpose of a loop test condition?
- What is meant by the term main programming loop?
^ top
Exercise 4.3
Specifications
- Save the following code as
guess.cpp.
- Update the guessing game code to let the user make as many guesses as they choose.
- Decide which statements need to repeat
- Write the while loop with a condition for exiting the loop
- Initialize the loop variables so the loop can run at least once
- Submit your program along with your other exercises for this lesson.
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;
cout << "I'm thinking of a number between"
<< " 1 and 10.\nCan you guess it?\n";
cin >> guess;
if (guess == 7) {
cout << "*** Correct! ***\n";
} else {
cout << "Sorry, that is not correct.\n";
}
return 0;
}
|
^ top
4.4: 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
4.4.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
4.4.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
4.4.3: Accumulating Values
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 <= 5
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 count = 1
while count <= 5
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
|
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int count = 1;
while (count <= 5) {
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
4.4.4: Running Totals
- Let us look at how to accumulate numbers when we do not know how many numbers there are in the list
- 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
- The first change is easy -- we know how to print numbers!
- For the second change, the specification gives us a hint
- We exit the loop when the user enters a number
- 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?
^ top
4.4.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
4.4.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 4.4
Background
Recall from lesson 3.3.2 that you can add numbers to a char data type. Also recall that you can cast a char to an int to get its numerical equivalent.
Specifications
- Save the following code as
ascii.cpp
- Modify the code to list the integer count and ASCII characters numbered from 1 through 255 like the following excerpt:
65: A
66: B
67: C
- Submit your program 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
Wrap Up
^ top
Home
| WebCT
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: October 13 2005 @15:15:14
|