Chapter 5:
Repetition and Loop Statements
Problem Solving,
Abstraction, and Design using C++ 6e
by Frank L. Friedman and Elliot B. Koffman
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Control Structures
• Sequence
• Selection
• Repetition
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
2
5.1 Counting Loops and while
• Loop – a control structure that repeats a
group of statements in a program
• Loop body – the statements that are
repeated in a loop
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
3
Counter-Controlled Loop
• Repetition managed by a loop control
variable whose value represents a count
• Counting Loop
– Set loop control variable to an initial value of 0
– While loop control variable < final value
•…
• Increase loop control variable by 1
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
4
Counter-Controlled Loop
• Used when we can determine prior to loop
execution how many loop repetitions will
be needed to solve problem
• Number of repetitions should appear as the
final count in the while condition
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
5
Listing 5.1
Program fragment with a loop
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
6
The while Statement - Example
• Loop Body
– Compound statement
– Gets an employee’s payroll data
– Computes and displays employee’s pay
• After 7 weekly pay amounts are displayed,
the statement following loop body executes
– Displays message “All employees processed.”
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7
The while Statement - Example
• countEmp = 0;
– Sets initial value of 0, representing the count of
employees processed so far
• Condition evaluated (countEmp < 7)
– If true, loop body statements are executed
– If false, loop body is skipped and control passes
to the display statement (cout) that follows the
loop body
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
8
The while Statement - Example
• countEmp = countEmp + 1;
– Increments the current value of the counter by 1
• After executing the last statement of the
loop body
– Control returns to the beginning of the while
– The condition is reevaluated
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
9
Loop Repetition Condition
•
•
•
•
Follows while reserved word
Surrounded by parentheses
When true, the loop body is repeated
When false, exit the loop
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
10
Figure 5.1
Flowchart for a while loop
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
11
Loop Control Variable
• Initialize
• Test
• Update
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
12
while Statement Syntax
• Form
while (loop repetition condition)
statement;
• E.g.
countStar = 0;
while (countStar < n)
{
cout << “*”;
countStar = countStar + 1;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
13
Loop Notes
• If the loop control variable is not properly
updated, an infinite loop can result.
• If the loop repetition condition evaluates to
false the first time it’s tested, the loop body
statements are never executed.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
14
5.2 Accumulating a Sum or
Product in a Loop
• Loops often accumulate a sum or product
by repeating an addition of multiplication
operation.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
15
Listing 5.2
Program to compute company payroll
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
16
Listing 5.2
Program to compute company payroll
(continued)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
17
Example – Compute Payroll
• Initialization statements
totalPay = 0.0;
countEmp = 0;
// pay accumulator
// loop control variable that
// counts number of
// employees processed
• Accumulation
totalPay = totalPay + pay;
// add next pay
• Incrementation
countEmp = countEmp + 1;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
18
Writing General Loops
• Process exactly 7 employees
while (countEmp < 7)
• Process an indefinite number of employees;
number of employees must be read into
variable numberEmp before the while
statement executes
while (countEmp < numberEmp)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
19
Multiplying a List of Numbers
product = 1;
while (product < 10000)
{
cout << product << endl;
// display product so far
cout << “Enter data item: “;
cin >> item;
product = product * item;
// update product
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
20
Conditional Loop
1. Initialize the loop control variable
2. While a condition involving the loop
control variable is true
3. Continue processing
4. Update the loop control variable
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
21
Compound Assignment Operators
• General form of common operations
variable = variable op expression;
• E.g.
countEmp = countEmp + 1;
time = time - 1;
totalPay = totalPay + pay;
product = product * item;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
22
Special Assignment Operators
• += -= *= /= %=
• general form
variable op= expression;
• E.g.
countEmp += 1;
time -= 1;
totalPay += pay;
product *= item;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
23
The for Statement
• Especially useful for counting loops
• Form
for (initializing expression;
loop repetition condition;
update expression)
statement;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
24
The for Statement
• E.g.
for (countStar = 0;
countStar < N;
countStar += 1;
cout << “*”;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
25
Listing 5.3
Using a for statement in a counting loop
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
26
Formatting the for Statement
• Placement of expressions can be on one line
or separate lines
• Body of loop indented
• Position of { } align with for keyword on
separate lines (style for this book)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
27
Increment and Decrement
Operators
• ++ -• Apply to a single variable
• Side effect - a change in the value of a
variable as a result of carrying out an
operation
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
28
Increment and Decrement
Operators
• Prefix operator
– E.g.
m = 3;
n = ++m;
• Postfix operator
– E.g.
m = 3;
n = m++;
• Often used to update loop control variable
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
29
Listing 5.4
Function to compute factorial
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
30
Localized Declarations of
Variables
• Commonly used for loop control variables
• Declared at point of first reference
• Value has meaning (i.e. can be referenced)
only inside loop.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
31
Example - Localized Variables
string firstName;
cout << “Enter your first name: “’
cin >> firstName;
for (int posChar = 0;
posChar < firstName.length( );
posChar++;)
cout << firstName.at(posChar) << endl;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
32
Listing 5.5
Converting Celsius to Fahrenheit
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
33
Listing 5.5
Converting Celsius to Fahrenheit (continued)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
34
Output - Celsius to Fahrenheit
Celsius
10
5
0
-5
Fahrenheit
50.00
41.00
32.00
23.00
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
35
Displaying a Table of Values
• setw( ) manipulator helps create neat
columns
• It is a member function of the iomanip
class.
• Requires the iomanip library to be included
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
36
Conditional Loops
• Used when you can’t determine before loop
execution begins exactly how many loop
repetitions are needed.
• The number of repetitions is generally
stated by a condition that must remain true
in order for the loop to continue.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
37
Conditional Loop
Initialize the loop control variable.
While a condition involving the loop control
variable is true
Continue processing.
Update the loop control variable
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
38
Case Study: Monitoring Oil Supply
• Problem We want to monitor the amount of oil
remaining in a storage tank at the end of each day.
The initial supply of oil in the tank and the amount
taken out each day are data items. Our program
should display the amount left in the tank at the
end of each day and it should also display a
warning when the amount left is less than or equal
to 10 percent of the tank’s capacity. At this point,
no more oil can be removed until the tank is
refilled.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
39
Case Study: Analysis
• Clearly, the problem inputs are the initial oil
supply and the amount taken out each day. The
outputs are the oil remaining at the end of each
day and a warning message when the oil left in the
tank is less than or equal to 10 percent of its
capacity.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
40
Case Study: Data Requirements
• Problem Constants
CAPACITY = 1000
MINPCT = 0.10
// tank capacity
// minimum %
• Problem Input
float supply
// initial oil supply
Each day’s oil use
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
41
Case Study: Data Requirements
• Problem Output
float oilLevel
// final oil amount
Each day’s oil supply
A warning message when the oil supply is less
than minimum.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
42
Case Study: Data Requirements
• Program Variable
float minOil
// minimum oil supply
• Formulas
Minimum oil supply is 10 percent of tank’s
capacity
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
43
Case Study: Initial Algorithm
1.Get the initial oil supply.
2.Compute the minimum oil supply.
3.Compute and display the amount of oil left
each day (implement as function
monitorOil).
4.Display the oil left and a warning message
if necessary.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
44
Analysis for Function monitorOil
• Function monitorOil must display a table
showing the amount of oil left at the end of
each day. To accomplish this, the function
must read each day’s usage and deduct that
amount from the oil remaining. The
function needs to receive the initial oil
supply and the minimum oil supply as
inputs (arguments) from the main function.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
45
Function Interface for monitorOil
• Input Parameters
float supply
float minOil
// initial oil supply
// minimum oil supply
• Output
Returns the final oil amount
• Local Data
float usage // input from user - each day’s oil use
float oilLeft // output from user - each day’s oil supply
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
46
Design of monitorOil
• The body of monitorOil is a loop that displays the oil
usage table. We can’t use a counting loop because we
don’t know in advance how many days if will take to bring
the supply to the critical level. We do know the initial
supply of oil, and we know that we want to continue to
compute and display the amount of oil remaining (oilLeft)
as long as the amount of oil remaining does not fall below
the minimum. So the loop control variable must be
oilLeft. We need to initialize oilLeft to the initial supply
and to repeat the loop as long as oilLeft > minOil is true.
The update step should deduct the daily usage (a data
value) from oilLeft.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
47
Initial Algorithm for monitorOil
1.Initialize oilLeft to supply.
2.While (oilLeft > minOil)
2.1 Read in the daily usage.
2.2 Deduct the daily usage from oilLeft
2.3 Display the value of oilLeft
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
48
Listing 5.6
Program to monitor oil supply
// File: oilSupply.cpp
Displays daily usage and amount left in oil tank.
#include <iostream>
using namespace std;
float monitorOil(float, float);
int main()
{
const float CAPACITY = 10000;
const float MINPCT = 10.0;
float supply;
float oilLeft;
float minOil;
// tank capacity
// minimum percent
// input - initial oil supply
// output - oil left in tank
// minimum oil supply
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
49
Listing 5.6
Program to monitor oil supply (continued)
// Get the initial oil supply.
cout << "Enter initial oil supply: ";
cin >> supply;
// Compute the minimum oil supply.
minOil = CAPACITY * (MINPCT / 100.0);
// Compute and display the amount of oil left each day
oilLeft = monitorOil(supply, minOil);
// Display warning message if supply is less than minimum
cout << endl << oilLeft << " gallons left in tank."
<< endl;
return 0;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
50
Listing 5.6
Program to monitor oil supply (continued)
float monitorOil(float supply, float minOil)
{
// Local data . . .
float usage;
// input from user - Each day's oil use
float oilLeft;
// Amount left each day
oilLeft = supply;
while (oilLeft > minOil)
{
cout << "Enter amount used today: ";
cin >> usage;
oilLeft -= usage;
cout << "After removal of " << usage << " gallons, ";
cout << "number of gallons left is " << oilLeft
<< endl << endl;
}
return oilLeft;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
51
Case Study: Testing
• To test the program, try running it with a few
samples of input data. One sample should bring
the oil level remaining to exactly 10 percent of the
capacity. For example, if the capacity is 10,000
gallons, enter a final daily usage amount that
brings the oil supply to 1,000 gallons and see what
happens.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
52
Case Study: Testing
Enter initial oil supply: 7000
Enter amount used today: 1000
After removal of 1000 gallons, number of gallons left is 6000
Enter amount used today: 4000
After removal of 4000 gallons, number of gallons left is 2000
Enter amount used today: 1500
After removal of 1500 gallons, number of gallons left is 500
500 gallons left in tank
Warning - amount of oil left is below minimum!
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
53
5.5 Loop Design and Loop
Patterns
initialization
• Sentinel-Controlled Loops
1. Read the first data item.
2. While the sentinel value has not been read
3. Process the data item.
4. Read the next data item.
update
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Loop repetition condition
54
Sentinel-Controlled Loops
• A sentinel is a specific predetermined value
used to terminate one type of eventcontrolled loop
• It is the same type as the other data being
processed
• It is outside the range of valid values for the
data
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
55
Example: Sum Exam Scores
1.Initialize sum to zero
2.Read first score
3.While score is not the sentinel
4. Add score to sum
5. Read next score
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
56
Listing 5.7
A sentinel-controlled loop
// File: sumScores.cpp
// Accumulates the sum of exam scores.
#include <iostream>
using namespace std;
void displayGrade(int);
int main()
{
const int SENTINEL = -1;
int score;
int sum;
int count;
int average;
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
57
Listing 5.7
A sentinel-controlled loop (continued)
// Process all exam scores until sentinel is read
count = 0;
sum = 0;
cout << "Enter scores one at a time as requested." << endl;
cout << "When done, enter " << SENTINEL << " to stop."
<< endl;
cout << "Enter the first score: ";
cin >> score;
while (score != SENTINEL)
{
sum += score;
count++;
displayGrade(score);
cout << endl << "Enter the next score: ";
cin >> score;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
58
Listing 5.7
A sentinel-controlled loop (continued)
cout << endl << endl;
cout << "Number of scores processed is " << count
<< endl;
cout << "Sum of exam scores is " << sum << endl;
// Compute and display average score.
if (count > 0)
{
average = sum / count;
cout << "Average score is " << average;
}
return 0;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
59
Listing 5.7
A sentinel-controlled loop (continued)
// Displays the letter grade corresponding to an exam
// score assuming a normal scale.
void displayGrade(int score) // IN: exam score
{
if (score >= 90)
cout << “Grade is A” << endl;
else if (score >= 80)
cout << “Grade is B” << endl;
else if (score >= 70)
cout << “Grade is C” << endl;
else if (score >= 60)
cout << “Grade is D” << endl;
else
cout << “Grade is F” << endl;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
60
Testing: sumScores
Enter the scores one at a time as requested.
When done, enter -1 to stop.
Enter the first score: 85
Grade is B
Enter the next score: 33
Grade is F
Enter the next score: 77
Grade is C
Enter the next score: -1
Number of scores processed is 3
Sum of exam scores is 195
Average score is 65
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
61
Calculating an Average
• Requires keeping a count of the number of
values processed (e.g. count in sumScores)
• Counter is initialized to zero before loop
begins
• Counter is incremented (e.g. count++; )
within loop body
• Counter is not the loop control variable in
this case
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
62
Flag Controlled Loops
initialization
1. Set the flag to false.
2. While the flag is false
3. Perform some action.
4. Reset the flag to true if the anticipated
event occurred.
Loop repetition condition
update
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
63
Flag Controlled Loops
• Type bool variables often used as flags
• Flag initialized to false before loop entry
• Flag reset to true when a particular event
occurs
• Note: because flag is initially false, the loop
condition uses ! (not) operator to reverse the
flag’s value
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
64
Listing 5.8 Function getDigit
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
65
5.6 The do-while Statement
• The do while statement is similar to the
while loop, but the do while loop has the
test at the end. General form:
do
{
statement;
} while ( expression ) ;
• Notice the iterative part executes before the
loop-test)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
66
Data-validation Loop
• do
prompt for and read a data item
while data item is not valid
• E.g.
do
{
cout << “Enter number of employees: “;
cin >> numEmp;
} while (numEmp < 0);
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
67
Listing 5.9
Function getIntRange
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
68
do-while and Menus
• Often used to control a menu-driven
program
• Display a list of choices for user to select
from
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
69
Typical Menu
List of edit operations:
D - Delete a substring
F - Find a string
I - Insert a string
R - Replace a substring
Q - Quit
Enter D, F, I, R, or Q as your selection:
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
70
Main Control Routine
do
Display the menu
Read the user’s choice
Perform the user’s choice
Display the edited string
while the choice is not Quit
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
71
Listing 5.10
Main function for text editor program
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
72
Listing 5.10
Main function for text editor program
(continued)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
73
Listing 5.11
Finding the largest value
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
74
Listing 5.11
Finding the largest value (continued)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
75
5.7 Review of Loop Forms
• while
– most commonly used when repetition is not
counter controlled
– condition test precedes each loop repetition
– loop body may not be executed at all
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
76
Review of Loop Forms
• for
– used to implement a counting loop
– also convenient for other loops with simple
initialization and update steps
– condition test precedes the execution of the
loop body
– loop body may not be executed at all
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
77
Review of Loop Forms
• do-while
– convenient when at least one repetition of the
loop body is required
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
78
5.8 Nested Loops
• As with if statements, loop statements can
be nested
• Each time outer loop is repeated, any inner
loop is restarted - loop control components
are reevaluated and all required iterations
are performed
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
79
Listing 5.13
Nested for loop program
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
80
Listing 5.13
Nested for loop program (continued)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
81
Listing 5.14
Displaying the multiplication table
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
82
Listing 5.14
Displaying the multiplication table (continued)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
83
5.9 Debugging and Testing
Programs
• Modern Integrated Development
Environments (IDEs) include features to
help you debug a program while it is
executing.
• If you cannot use a debugger, insert extra
diagnostic output statements to display
intermediate results at critical points in your
program.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
84
Debugging Without a Debugger
• Insert diagnostic output statements
– at locations where you suspect things are going
wrong or other critical points in the code
• beginning and end of functions
• after complex calculations
– to display intermediate results, e.g. variables
affected by each major algorithm step
• Remove extra output statements when
problem solved, or use // to “comment out”
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
85
Off-by-one Errors
• Common logic error - a loop that executes
one time too many or one time too few
• Check initial and final values for loop
control variables
• Check loop repetition condition
• Check loop boundaries during testing
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
86
Testing
• Thorough testing necessary
• Check all paths through decision statements
and the number of iterations for loops
• Make enough test runs to verify that the
program works properly for representative
samples of all possible data combinations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
87
5.10 Common Programming Errors
•
•
•
•
•
•
•
•
Omitting braces ( { })
Omitting a closing brace ( } )
Infinite loop
Misuse of = for ==
Bad sentinel value
Using do-while instead of while
Incorrect use of compound assignment
Incorrect use of increment and decrement
operators
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
88
Loops in graphics programs - quilt
The program in Listing 5.15 draws a "quilt" consisting of nested filled rectangles. It
first draws a large black bar which fills the output window. Each subsequent bar is
centered inside the previous one, overwriting its pixels in a new color, so only a
border from the previous rectangle remains on the screen.
•
•
•
•
The statements
stepX = width / (2 * numBars);
// x increment
stepY = height / (2 * numBars);
// y increment
define the change in x- and y-values for the corners of each bar and are computed so
that there will be room to display all the bars.
•
•
•
•
•
•
In the for loop, the statements
foreColor = i % 16;
// 0 <= foreColor <= 15
setcolor(foreColor);
setfillstyle(i % 12, foreColor); // set fill style.
bar(x1, y1, x2, y2);
// draw a bar.
set the foreground color to one of 16 colors, based on the value of loop variable i.
Similarly, function setfillstyle sets the fill pattern to one of 12 possible patterns.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
89
Quilt cont’d
• After each bar is drawn, the statements
• x1 = x1 + stepX; y1 = y1 + stepY;
// change top left
• x2 = x2 - stepX; y2 = y2 - stepY;
// change bottom right
• change the top-left corner (point x1, y1) and the
bottom-right corner (point x2, y2) for the next bar,
moving them closer together.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
90
Quilt Program
#include <graphics.h>
#include <iostream>
using namespace std;
int main()
{
int x1, y1, x2, y2;
int stepX, stepY;
int foreColor;
int numBars;
int width, height;
//
//
//
//
//
coordinates of corner points
change in coordinate values
foreground color
number of bars
screen width and height
cout << "Enter number of bars: ";
cin >> numBars;
width = getmaxwidth();
height = getmaxheight();
initwindow(width, height, "Quilt");
// Set corner points of outermost bar and
// set increments for inner bars
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
91
Quilt Program cont’d
x1 = 0;
y1 = 0;
x2 = width;
y2 = height;
stepX = width / (2 * numBars);
stepY = height / (2 * numBars);
// Draw nested bars
for (int i = 1; i <= numBars; i++)
{
foreColor = i % 16;
setcolor(foreColor);
setfillstyle(i % 12, foreColor);
bar(x1, y1, x2, y2);
x1 = x1 + stepX; y1 = y1 + stepY;
x2 = x2 - stepX; y2 = y2 - stepY;
}
getch();
closegraph();
return 0;
//
//
//
//
top left corner
bottom right corner
x increment
y increment
// 0 <= foreColor <= 15
//
//
//
//
Set fill style
Draw a bar
Change top left corner
Change bottom right
// pause
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
92
Quilt
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
93
Animation
• In graphics animation, motion is achieved by displaying a
series of frames in which the object is in a slightly different
position in the current frame than it was in the previous frame,
so it appears that the object is moving. Each frame is displayed
for a few milliseconds.
• Like flip-books for children in which objects were drawn in
slightly different positions on each page of the book. As you
flipped the pages, the object moved.
• The program in Listing 5.16 draws a ball that moves around
the screen like the ball in a pong game. It starts moving down
the screen and to the right until it reaches a "wall" (a window
edge) and then reverses its x- or y-direction depending on
which wall it hit.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
94
Double Buffering
• A technique called double buffering reduces the screen flicker
and makes the motion seem smoother.
• In single buffering, a single memory area (or buffer) is used to
hold the frame that will be shown next on the screen. After the
buffer is filled, its bytes are sent to the graphics hardware for
display. When done, the bytes for the next frame are loaded into
the buffer.
• In double buffering, while the bytes in one buffer are being sent
to the graphics display, the second buffer is being filled with the
bytes for the next frame. Then, the contents of the second buffer
are sent to the graphics hardware, while the first buffer is being
filled. The extra buffer enables the screen display to be refreshed
more frequently, resulting in less flicker between transitions. In
graphics.h, double-buffering is turned on by setting the sixth
argument for initwindow to true.
initwindow(width, height,
"Pong - close window to quit", 0, 0, true);
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
95
Program to Draw Moving Ball
// File animate.cpp
// Draws a ball that moves around the screen like in pong
#include <graphics.h>
using namespace std;
int main()
{
const int PAUSE = 20;
// delay between frames
const int DELTA = 5;
// change in x or y value
const int RADIUS = 30;
// ball radius
const int COLOR = RED;
int
int
int
int
int
width;
height;
x; int y;
stepX;
stepY;
//
//
//
//
//
width of screen
height of screen
center of ball
increment for x
increment for y
// Open a full-screen window with double buffering
width = getmaxwidth();
height = getmaxheight();
initwindow(width, height, "Pong - close window to quit", 0, 0, true);
x = RADIUS; y = RADIUS;
stepX = DELTA; stepY = DELTA;
// Start ball at top-left corner
// Move down and to the right
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
96
Program to Draw Moving Ball cont’d
// Draw the moving ball
while (true) {
// Clear the old frame and draw the new one.
clearviewport();
setfillstyle(SOLID_FILL, COLOR);
fillellipse(x, y, RADIUS, RADIUS); // Draw the ball
// After drawing the frame, swap the buffers
swapbuffers();
delay(PAUSE);
// If ball is too close to a window boundary, change direction
if (x <= RADIUS)
// Is ball too close to left/right edge?
stepX = DELTA;
// Move right
else if (x >= width - RADIUS)
stepX = -DELTA;
// Move left
if (y <= RADIUS)
// Is ball too close to top/bottom?
stepY = DELTA;
// Move down
else if (y >= height - RADIUS)
stepY = -DELTA;
// Move up
// Move the ball
x = x + stepX;
y = y + stepY;
}
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
97
Changing the Ball Direction
•
•
•
•
•
•
•
The loop executes "forever", or until the user closes the window. The loop begins by
clearing the window for the new frame (function clearviewport). Next, it draws the
ball in the new frame (stored in the second buffer). Then the buffers are swapped
(function swapbuffers) and there is a delay of 20 milliseconds while the ball is
displayed in its new position.
swapbuffers();
delay(PAUSE);
The if statements change the direction of motion when the ball reaches an edge. In the
statement below, the first condition is true if the current x position is closer to the left
edge than the radius of the ball. In that case, the ball should move to the right (stepX
is positive).
if (x <= RADIUS)
// Is ball too close to left/right edge
stepX = DELTA;
// Move right
else if (x >= width - RADIUS)
stepX = -DELTA;
// Move left
The condition directly above is true if the x position of the ball is to too close to the
right edge, so the ball should move to the left (stepX is negative). The assignment
statements at the end of the loop compute the position of the ball for the next frame.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
98
Trace of Moving Ball
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
99
© Copyright 2026 Paperzz