# Computing Fundamentals with C++

Document Sample

```					C++ and Object-Oriented
Programming
Flow Control: Repetition (Looping)

8-1
Repetition: Looping

 Goals
   Recognize and use the Determinate Loop pattern
   Recognize and use the indeterminate loop pattern
– Exercises
– Programming Projects
   Use the C++ do while statement
   Design Loops
– Exercises
– Programming Projects
   There are two sets of exercises and programming projects
8-2
Repetitive Control

 The   following algorithms involve repetition:
   Add the remaining flour ¼ cup at a time
whipping until smooth.
   While there are more burger/fries/soda orders,
sum each item. Apply tax. Display Total.
   Compute a course grade for every student.
   While the ATM is running, process another
customer, and allow many transactions.
   Microwave the food until the timer reaches 0, the
cancel button is hit, or the door is opened. 8-3
Why is repetition needed?

 To take advantage of the computer's
speed in order to perform the same tasks
faster.
 To avoid writing the same statements
over and over again (shorter programs).
 To traverse a collection of objects.
 To make programs general enough to
handle various sized collections of data.
 Consider code intended to average        8-4
Average 100 values the hard way

int sum = 0;
cout << "Enter number: "; // <-Repeat these three
cin >> number;            // <- statements for each
sum = sum + number;       // <- number in the set
cout << "Enter number: ";
cin >> number;
sum = sum + number;

// ...291 statements deleted ...

cout << "Enter number: ";
cin >> number;
How many statements are
sum = sum + number;         required for 100 inputs____?
average = sum / 100;
What changes are necessary to
average 200 inputs ____? 8-5
Algorithmic Pattern:
The Determinate loop

 There  is a better way.
 We often need to perform some action a
specific number of times:
   Produce 89 paychecks.
   Count down to 0 (take 1 second of the clock).
   Send grade reports to 75,531 Penn State students
 The determinate loop pattern repeats some
action a specific number of times.
8-6
Pattern:   Determinate Loop
Problem: Do something exactly n times, where n is
Algorithm determine n
repeat the following n times
{
perform these actions
}
cout << "Enter n: ";
Code      cin >> n;
Example:    for (j = 1; j <= n; j = j +   1)
{
cout << "Enter number: ";   // Repeat
cin >> number;              // these
sum = sum + number;         // statements
}
8-7
Determinate Loops

 This  template repeats a process n times (you
n = /* how often we must repeat the process */
for (count = 1; count <= n; count = count + 1)
{
/* the process to be repeated */
}
   determinate loops must know the number of
repetitions before they begin
   know exactly how many employees, or students, or
whatever, that must be processed.
8-8
The C++ for loop--determinate loops

for ( initial statement ; loop-test ; update-step )
{
repeated-part
}

   When a for loop is encountered, the initial-statement is
executed. The loop-test evaulates. If the loop-test is false,
the for loop is terminated. If loop-test is true, the repeated-
part is executed and the update-step executes.
8-9
Flow chart view of a for loop

Initial statement

False                       True
Loop test

Iterative part

update-step

8-10
Example for loop that produces an
average
int n;
double number, ave
double sum = 0.0;
// get a value for the number of iterations
cout << "How many numbers? ";
cin >> n;
for(int counter = 1; counter <= n; counter = counter + 1)
{ // Iterate the same three statements n times
cout << "Enter number: ";
cin >> number;
sum = sum + number;
}
// Compute and display the average (pre: n > 0)
ave = sum / n;
cout << "Average: " << ave << endl;
8-11
Demonstration

 Active   Learning, Write the output :
int j, n = 5;
for(j = 1; j <= n; j = j + 1)
{
cout << j << endl;
}

for(int k = 10; k >= 0; k = k - 2)
{
cout << k << endl;
}

Optional Demo forloops.cpp
8-12
Other Incrementing Operators
 Itis common to see determinate loops of this
form where n is the number of repetitions
for(j = 1; j <= n; j++) {
// ...

 The unary ++ and -- operators add 1 and
subtract 1 from their operands, respectively.
int n =   0;
n++; //   n is now 1 Equivalent to n=n+1; or n+=1;
n++; //   n is now 2
n--; //   n is now 1 again

 Theexpression count++; is equivalent to the
more verbose count = count + 1;         8-13
Other Assignment Operators

 C++has several assignment operators in
addition to = (-= and +=)
j -= 2; is the equivalent of j = j - 2;
sum += x; is the equivalent of sum = sum + x;
 What   is sum when a user enters 7 and 8?
int sum = 0, x   = 0;
cout << "Enter   a number: ";
cin >> x;   //   user enters 7
sum += x;
cout << "Enter   a number: ";
cin >> x;   //   user enters 8
sum += x;
8-14
Determinate loops with grid objects

code surrounds the grid with blocks,
 This
no matter what its size is:
for(r = 0; r < g.nRows(); r++)
{
g.block(r, 0);                // block west
g.block(r, g.nColumns() - 1); // block east
}

for(c = 1; c < g.nColumns() - 1; c++)
{
g.block(0, c);                // block north
g.block(g.nRows() - 1, c);    // block south
}
8-15
Application of the determinate loop
pattern

 Find  the range of test scores where range is
defined as the highest minus the lowest.
 So if the input of 4 test scores is 70, 80, 90, and
100, then what is the range _____?
 Prelude to the range problem:
   Imagine finding the largest number in a list of
thousands of numbers––we need a systematic
method (we can’t just glance at the list).
8-16
Analysis

 Problem:  Write a program that determines a
range (highest-lowest) of tests. The user must
enter the number of tests to check.
 Inputs: The number of test scores to scan, and
The actual test scores.
 Output: The range
 Active Learning: Name the objects we’ll need
_________ _________ _______ _______
8-17
Design

 Start   with this algorithm
1. Obtain the number of test scores.
2. Determine the range.
3. Display the range.
 You  might notice that the process step,
"Determine the range", needs further
refinement
 The first step is a prompt/input pattern
and the third step is simply labeled output.
8-18
Design (con.)
// 1. Obtain the number of test scores
cout << "Enter number of test scores: ";
cin >> n;

////////////////////////////
// 2. Determine the range //
////////////////////////////

// 3. Display the range
cout << "Range = " << range;

   So let's concentrate on the second step.
   Since range is defined as highest-lowest, we need to find
the highest and lowest.
8-19
Design (con.)

 We  need the actual test scores for input to
determine the highest and lowest.
 As each new test score is input, we
compare it to the highest so far, and also
to the lowest so far.
 But what do we compare the first test to?
   How about something very large for the smallest
and something very small for the largest.
   Then the first number is compared to these “fake”
values.                                           8-20
Design (con.)

 Ina side by side comparison, we see test
is greater than the fake largest (-1000) and
less than the fake smallest (+1000)
1000
smallest
500                  test

0                  largest

-500

-1000
8-21
Design (con.)
 So,before we start reading tests, let’s
initialize highest and lowest like this:
double highest = -1000;
double lowest = +1000;

 Then   we need to do the following n times
Input a test.
Compare test to highest,           Trace algorithm
and if necessary, store the             with inputs of
test as the highest so far.                 87 91 72
Compare test to lowest,
and if necessary, store the    test    ?     87 91 72
test as the lowest so far.     highest -1000 87 91 91
72
lowest +1000 87 878-22
Use the “determinate loop" pattern
again

 We do this n times. Do you see the
pattern?
// 2. Determine the range            Demonstrate range.cpp
for(counter = 1; counter <= n; counter++)
{
// The process to repeat n times
cout << "Enter test: ";
cin >> test;
if (test > highest)
highest = test;
// check for lowest ? _______ ?
}
// assert: highest stores the largest test
//          and lowest stores the smallest test          8-23
Why bother?

 Itshould be noted, that this computer based
range problem is more cumbersome than just
scanning a small list of tests for the highest
and lowest.
 But imagine thousands of inputs in a file
which we cannot see.
 We could use the same pattern, but someone
must count the inputs before starting.
 There must be a better way.
8-24
Algorithmic pattern:
The Indeterminate Loop
 Determinate     loops have a limitation
   We must know n in advance.
 Many situationswhen repeat a set of
statements an unspecified number of times:
   Processing report cards for every student in a school
(or paychecks for all employees, or...)
   Allowing 1 to many ATM transactions.
   Asking the user for specific input and allowing re-
entry of input after invalid inputs.

NAME ANOTHER: ? ________________ ?                   8-25
Some Events that terminate
indeterminate loops
 An  indeterminate loop repeats a process until some
stopping event terminates the repetition.
 There are many such events, but we'll focus on these
events only:
    User enters a special value indicating end of data.
    A logical expression becomes false.
    The grid mover hits the wall or an edge
    The end of a file is encountered.
do not need to know n in
 indeterminate loops
8-26
Pattern:    indeterminate loop

Problem:    Some process must repeat an unknown number
of times so some event is needed to terminate
the loop.

Algorithm   while(the termination event has not occurred)
{
perform these actions
bring the loop closer to termination
}

Code        while(myGrid.frontIsClear())
Example     {
myGrid.putDown();
myGrid.move();
}
8-27
The while loop

indeterminate loop pattern can be imple-
 The
mented with the C++ while loop there are other ways
while ( loop-test )
{
repeated-part
}
 When a while statement is encountered the block
(statements between { and } )execute while (as
long as) the loop-test is true.
8-28
Flow chart view of while-loop execution

False                 True
loop-test
statement-1
Iterative
statement-2   Part

statement-n

8-29
Using while to Implement Determinate
loops
 This  loop terminates when j <= n becomes
false.
 The event that terminates this loop is j > n
int j = 1;
int n = 4;
while(j <= n)
{
cout << j << " ";
j++;
}

Output: _______ ?
8-30
indeterminate loop pattern with grid
objects
grid g(5, 10);
// assert: g is a 5x10 grid surrounded by blocks
// with one opening and the mover in a random spot
while(g.frontIsClear())
{
g.move(1);
}
g.display();
// Output (exit could be anywhere on an edge)
# # # # # # # # # #
# . . . . . . . . #
# <               .
# . . . . . . . . #
# # # # # # # # # #
8-31
indeterminate loop with a Sentinel

A sentinel is a specific input from the user ot
signal that there is no more data.
   The sentinel should be the same type of dats
   The sentinel must not be in the valid range of
data
   Example: Use -1 as the sentinel for test scores
that can only be in the range of 0 through 100
Enter test scores or -1 to quit:
80 95 76 82 56 100 45 86 -1

8-32
Using cin >> as a loop test

 An extraction itself may exist as a loop-test in
an if...else or while statement:
   if(cin >>intObject) or while(cin >>intObject)
 This   simplifies the loop
// Priming extraction is part of the loop test
while( (cin >> test) && (test != -1) )
{ // now process the test
sum += test;
n++;
}

8-33
Using stream extraction as a loop test

 Example  evaluation of the loop-test when 95
is input for test:

while( (cin >> test) && (test != -1) )
(     true    ) && ( 95 != -1) )
true      &&      true
true

Demonstrate cin extraction as the loop-test with sentinel.cpp

8-34
Infinite loops

 Infinite   loop: a loop that never terminates.
   Infinite loops are usually not desirable.
   Here is an example of an infinite loop:
cin >> test;
while(test != -1)
{ // now process the test
sum += test;
n++;
}

   There is no step that brings the loop closer to
termination.
8-35
Loop Selection and Design

 The following outline is offered to help
you choose and design loops in a variety
of situations:
   Determine which type of loop to use
   Determine the loop-test
   Write the statements to be repeated
   Bring the loop one step closer to termination
   Initialize objects if necessary
8-36
Determine Which Type of Loop to Use

 Thenumber of repetitions is known in
controlled for loop. The loop must stop
when some event occurs during, use an
event-controlled while loop. When the
loop must always execute once (to
validate input), use a do-while loop
8-37
Determine the Loop-Test

 Trywriting the conditions that must be
true for the loop to terminate.
inputName == "QUIT" // Termination condition

 Thelogical negation (with ! applied) can
be used directly as the loop-test of a while
loop:
while( inputName != "QUIT") // logical negation

8-38
Write the Statements to be Repeated

 This is why the loop is being written in
the first place. This may be done after
other parts.
{
cout << "Enter number: ";
cin >> x;
sum = sum + x;
n++;
}

8-39
Bring the Loop one Step Closer to
termination

 Toavoid an infinite loop, there should be at
least one action in the loop body that brings it
closer to termination.
    Increment the counter by +1.
    Extract data from an input stream.

8-40
Initialize Objects if Necessary.

 Check  to see if any objects used in either the
body of the loop or the loop-test need to be
initialized. Consider this loop:
int j, n;
double x, sum;
while(j <= n)
{
cout << "Enter a number: ";
cin >> x;
sum = sum + x;
j++;
}
   Which objects need to be initialized before this while
loop is encountered ? _______________ ?
8-41

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 7 posted: 8/17/2012 language: pages: 41
How are you planning on using Docstoc?