cs 117 spring 2002 repetition hanly chapter 4 friedman-koffman chapter 5
Post on 21-Dec-2015
227 views
TRANSCRIPT
Flow Control
• Three types of program flow– sequential (what we did first)– selection (what we just looked at)
• if - else• switch
– repetition (Chapter 4)• while• do - while• for
Repetition
• There are many situations where you need to repeat the same actions over and over.– averaging a group of numbers– reading a file one line at a time– searching through a group of objects– repeating a calculation for different input
values
Why iterate?
Use the computer's speed to do the same task faster than if done by hand.
Avoid writing the same statements over and over again.
Repetitive control structures
– Because many algorithms require many iterations over the same statements.• To average 100 numbers, we would need
300 plus statements.• Or we could use a statement that has the
ability to repeat a collection of statements:
Sum 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;
Sum 100 values the hard way
/*
...291 statements deleted ...
*/
cout << "Enter number: ";
cin >> number;
sum = sum + number;
average = sum / 100;
2/15/02
• Questions about program 2
• Holiday Monday - building may be closed
• seminar Wed Feb 20
• using namespace
Loop Behaviorinitialize loop control variableexecute body of loopupdate loop control variablecontinue after loop
check loop control
var
FalseTrue
while loop
• Basic syntaxwhile (cond)
doSomething;• As in the if statement, the first statement after the
while is considered to be the body of the loop. Use { } to make it more than one statement.
• If the condition is false to begin with, the loop doesn’t execute at all.
Sentinel Loop
• Useful for finding the end of a list of numbers• if you know all valid data is positive, stop the loop
when a negative value is input
double data = 1.0while (data > 0.0) {
cin >> data;processData;}
readme
• your name, assignment
• instructions for using the program
• anything you did to try to get extra credit
• what you liked, disliked, had particular trouble with
• what you would like to do to make the program better
while loop
• Basic syntaxwhile (cond)
doSomething;• As in the if statement, the first statement after the
while is considered to be the body of the loop. Use { } to make it more than one statement.
• If the condition is false to begin with, the loop doesn’t execute at all.
5.4 Conditional Loops
In many programming situations, you will not be able to determine the exact number of loop repetitions
Conditional Loop– Initialize the loop control variable– While a condition involving the loop control
variable is true– Continue processing
– Update the loop control variable
Flag-Controlled Loops
char getDigit(){ char nextChar; bool digitRead; digitRead = false; while (!digitRead)
{ cin >> nextChar; digitRead = (('0' <= nextChar) &&
(nextChar <= '9')); } return nextChar;}
Counting Loop
• a loop that repeats a pre-defined number of times
int count = 0, maxCount=10;
while (count<maxCount)
{
doWhatever;
count = count +1;
}
for loop
• Counting loop so common there is a special loop statement to handle it.for (init; cond; update)
forBody;– init initializes the loop control variable– cond is the loop repetition condition– update updates the loop control variable
counting loop with for
• The counting loop from above becomes
for (count=0; count<10; count=count+1)
doWhatever;
A different loop orderinitialize loop control variableexecute body of loopupdate loop controlvariablecontinue after loop
check loop control
var
FalseTrue
do-while loop
• like while except loop control variable is checked after the body has executed char ch;do {
mainAction;cout << "Enter a character, q to quit ";cin >> ch;
} while (ch!='q');• the loop body always executes at least once.
loop cautions
while (cond);– has an empty body.
– Infinite loops: control variable doesn’t get changed so loop repeats forever
Program 3
• Program 3– Menu loop– Selection
• to select requested action
• converting between bearing and heading
– Alternate version slightly more difficult
Program 3
• Heading 0-360– N=0 = 360– S = 180– E = 90– W = 270
• Bearing – face north or south– degrees (0-90) to turn from
that direction– direction to turn - either
east or west
Loop Review :while
• Most commonly used when repetition is not counter controlled
• condition test precedes each loop repetition• loop body may not be executed at all
while (condition) dothis;
Loop Review: do-while
• Convenient when at least one repetition of loop body must be ensured
• test condition after execution of body
dothat;
while (condition);
Loop Overview
• Counting loop - number of repetitions – known ahead of time – can be controlled by a counter
• also convenient for loops involving non counting loop control with simple initialization and updates
• condition test precedes the execution
for (initialization; condition; modification)doSomething;
5.8 Nested Loops
Possible to nest loops – Loops inside other loops– Start with outer jump to inner loop– Inner loop continues until complete– Back to outer loop and start again
NestLoop.cpp and Triangle.cpp examples
Nested Logic
outer = 1;
while(outer <= 3)
{
inner = 1; // Resets for each iteration of the outer loop
while(inner <= outer)
{
cout << outer << " " << inner << endl;
inner = inner + 1;
} // End of the nested loop
outer = outer + 1; // Increment the outer loop counter
} // The end of the outer loop
increment and decrement operators
• For looping operations, you will frequently need to increment or decrement by 1.
• C++ has special operators, ++ and -- to do this.
– i++; is equivalent to i = i + 1;
– j--; is equivalent to j = j - 1;