Loop - West Chester University of Pennsylvania

Download Report

Transcript Loop - West Chester University of Pennsylvania

Loop
Loop
Loop
While Loop
Do-while Loop
For Loop
Continue Statement
Conclusion
While
Loop
Definition
General format
Example
Flow chart
Counter control repetition
Event control repetition
While loop
Action repeated while some condition
remains true
Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
while loop repeated until condition
becomes false
General format when using while loops
initialization;
While( LoopContinuationTest){
statement;
increment;
}
Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
Flowchart of while loop
true
product <= 1000
false
product = 2 * product
Counter-controlled repetition
Loop repeated until counter reaches certain
value
Number of repetitions known
Example
A class of ten students took a quiz. The
grades (integers in the range 0 to 100) for
this quiz are available to you. Determine the
class average on the quiz.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Class average program with counter-controlled repetition.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// function main begins program execution
int main()
{
int total;
// sum of grades input by user
int gradeCounter; // number of grade to be entered next
int grade;
// grade value
int average;
// average of grades
// initialization phase
total = 0;
// initialize total
gradeCounter = 1; // initialize loop counter
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// processing phase
while ( gradeCounter <= 10 ) {
// loop 10 times
cout << "Enter grade: ";
// prompt for input
cin >> grade;
// read grade from user
total = total + grade;
// add grade to total
gradeCounter = gradeCounter + 1; // increment counter
}
// termination phase
average = total / 10;
// integer division
// display result
cout << "Class average is " << average << endl;
The counter gets incremented each
time the loop executes.
return 0; // indicate program ended successfully
Eventually, the counter causes the
loop to end.
} // end function main
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Counter-controlled repetition requires
Name of control variable/loop counter
Initial value of control variable
• Declares counter to be an integer
int counter = 1;
• Names counter
• Sets counter to an initial value of 1
Condition to test for final value
Increment/decrement to modify control variable
when looping
Event-controlled repetition
Suppose problem becomes:
Develop a class-averaging program that will
process an arbitrary number of grades each
time the program is run
Unknown number of students
How will program know when to end?
Event
Indicates “end of data entry”
Loop ends when special input
• it cannot be confused with regular input
• -1 in this case
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
// Using the continue statement in a for structure.
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
ifstream fp(“data2.txt”); // open the file “data.txt”
int num;
Read
float grade, total=0;
String ssn;
all the information
inside the file until the read
mark reaches the end of file.
While ( !fp.eof()){
fp>>ssn >>grade;
total = total+ grade;
// sum of grades
num++;
} // end for structure while
cout << num << “students with average grades: " << total/num
<< endl;
return 0;
// indicate successful termination
}
Data2.txt
111-23-4561
123-15-1353
131-41-2626
245-51-1256
151-51-6437
134-59-6714
626-24-2266
536-24-2525
56
96
66
76
86
90
66
60
9 students with average grades: 72.8889
Do-While
Loop
General format
Example
General format when using do-while
loops
initialization;
do{
statement;
increment;
}while( LoopContinuationTest);
Example
int product = 2;
do {
product = 2 * product;
} while ( product <= 1000 );
For
Loop
General format
Example
Re-written
Initialization and increment for multiple
variables
Applications
for
Repetition Structure
General format when using for loops
for ( initialization; LoopContinuationTest;
increment )
statement
Example
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
Prints integers from one to ten
No
semicolon
after last
statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Counter-controlled repetition with the for structure.
#include <iostream>
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
// Initialization, repetition condition and incrementing
// are all included in the for structure header.
for ( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
return 0; // indicate successful termination
} // end function main
1
2
3
4
5
6
7
8
9
10
for loops can usually be rewritten as
while loops
initialization;
while ( loopContinuationTest){
statement
increment;
}
Initialization and increment for multiple
variables, use comma-separated lists
for (int i = 0, j = 0; j + i <= 10;
j++, i++)
cout << j + i << endl;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Summation with for.
#include <iostream>
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
int sum = 0;
// initialize sum
// sum even integers from 2 through 100
for ( int number = 2; number <= 100; number += 2 )
sum += number;
// add number to sum
cout << "Sum is " << sum << endl; // output sum
return 0;
// successful termination
} // end function main
Sum is 2550
Program to calculate compound interest
 A person invests $1000.00 in a savings account yielding 5
percent interest. Assuming that all interest is left on deposit
in the account, calculate and print the amount of money in
the account at the end of each year for 10 years. Use the
following formula for determining these amounts:
a = p(1+r)n
 p is the original amount invested (i.e., the principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the nth year
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Calculating compound interest.
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
using std::fixed;
#include <iomanip>
using std::setw;
using std::setprecision;
<cmath> header needed for
the pow (program will not
compile without it).
#include <cmath> // enables program to use function pow
// function main begins program execution
int main()
{
double amount;
// amount on deposit
double principal = 1000.0; // starting principal
double rate = .05;
// interest rate
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// output table column heads
cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;
// set floating-point number format
cout.self(ios::fixed,ios::floatfield);
cout.self(ios::showpoint);
cout << setprecision( 2 );
// calculate amount on deposit for each of ten years
for ( int year = 1; year <= 10; year++ ) {
// calculate new amount for specified year
amount = principal * pow( 1.0 + rate, year );
// output one table row
cout << setw( 4 ) << year
<< setw( 21 ) << amount << endl;
} // end for
return 0; // indicate successful termination
} // end function main
Sets the field width to at least
21 characters. If output less
than 21, it is right-justified.
pow(x,y) = x raised to the
yth power.
Year
1
2
3
4
5
6
7
8
9
10
Amount on deposit
1050.00
1102.50
1157.63
1215.51
1276.28
1340.10
1407.10
1477.46
1551.33
1628.89
Numbers are right-justified
due to setw statements (at
positions 4 and 21).
Continue
Statement
continue statement
Used in while, for, do/while
Skips remainder of loop body
Proceeds with next iteration of loop
while and do/while structure
Loop-continuation test evaluated
immediately after the continue statement
for structure
Increment expression executed
Next, loop-continuation test evaluated
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
// Using the continue statement in a for structure.
#include <iostream>
using std::cout;
using std::endl;
// function main begins program execution
int main()
{
// loop 10 times
for ( int x = 1; x <= 10; x++ ) {
Skips to next iteration of the
loop.
// if x is 5, continue with next iteration of loop
if ( x == 5 )
continue;
// skip remaining code in loop body
cout << x << " "; // display value of x
} // end for structure
cout << "\nUsed continue to skip printing the value 5"
<< endl;
return 0;
// indicate successful termination
26
27
} // end function main
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
Conclusion
While, do-while, and for loop
Counter-control and event-control
Many loops have three phases
Initialization
Initialize the program variables
Processing
Input data, adjusts program variables
Termination
Evaluate the condition and stop loop if necessary