Lect7.ppt

advertisement
Three C++ Looping
Statements
Chapter 7
CSIS 10A
1
Agenda
while loops 
for loops
designing for loops
user-controlled loops
debugging loops
2
Repetition, Repetition, Repetition
How can you repeat a block of statements ?
Keep calculating sphere volumes until radius of -1 is
entered
Calculate paychecks for 100 employees
Find the highest of a list of test scores
Print a table of Fahrenheit vs Celsius Temps
3
Initialization is key
Why we loop
Reduce and simplify repetitive code
Provide flexibility in how many values to process, etc.
TWO Common Loop tasks:
Counting:
count = 0;
count = count+1;
count = count+1;
count++;
cout << count;
Summing:
sum=0;
sum = sum + 8;
sum = sum + 3;
sum += 15;
cout << sum;
4
while-loop, fixed step
Flowchart: while-loop
n = 1;
n<=3
false
true
Display n
Add 1 to n
Display done
5
While Loop Statement
The previous flowchart illustrates a while-loop:
n = 1;
while (n <= 3)
{
cout << n << “ ”;
n = n + 1;
}
cout<< done <<endl;
Output:
1 2 3 done
6
while Loop Syntax
while (boolean expression is true)
{
statements to repeat ;
}
Semi-colons are used only to end the statements
within the loop (not after boolean expression)
while (boolean expression is true)
statement to repeat;
7
Your Turn
Can you
Show the output of this code?
x = 10;
while ( x > 0)
{
cout << x << endl;
x = x – 3;
}
Show the output of the previous code using the
comparison x < 0 instead of x > 0?
8
Your turn—What is the output?
1)
2)
x=0;
while (x < 10)
x=x+1;
cout << x << endl;
cout<< done <<endl;
x=0;
while (x < 10)
cout << x << endl;
x=x+1;
cout<< done <<endl;
9
Infinite Loops
Loops that never stop are infinite loops
The loop body should contain a line that will
eventually cause the boolean expression to
become false
Example: Print the odd numbers less than 12
x = 1;
while (x < 12)
Hit Ctrl-C to abort
{
cout << x << endl;
x = x – 2;
}
In this loop, make x larger: x=x+2;
See silent.cpp for a silent infinite loop!10
Repeating Calculations
Usually you use a loop to repeat some code
Step Controlled (Counted Loop):
repeat a certain number of times
User Controlled (Indefinite Loop):
repeat until a key value (sentinel) is entered
11
Simple Pay Calculation (no overtime)
// CALCPAY.CPP A program to calculate paychecks
int main( )
{ float hours, pay, rate;
cout << "enter hours and rate: ";
cin >> hours >> rate;
pay = rate * hours;
cout << "pay is " << pay;
}
Let’s see how to repeat this…
12
Step Controlled Loop Concept
Add a counter variable declaration
Set counter to initial value (usually 0)
while (counter < Max)
get input data
calculate result
display result
add 1 to counter
13
Step Controlled Loop Code
// CALCPAY.CPP A program to calculate paychecks
int main( )
{ float hours, pay, rate;
int count=0;
while(count<3)
{
cout << "enter hours and rate: ";
cin >> hours >> rate;
pay = rate * hours;
cout << "pay is " << pay;
count=count+1;
}
}
14
Step Controlled Loop using While
k=0;
// initialize counter
while(k<3)
// check counter
{
STATEMENTS TO REPEAT;
k=k+1;
// add 1 to counter
}
15
A Better Step Controlled Loop uses For
for( k=0; k<3; k=k+1 )
Or k++
{
STATEMENTS TO REPEAT;
}
More compact, easy to read, and works
exactly like the while loop (same flowchart)
16
Step Controlled Loop Code using For
// CALCPAY.CPP A program to calculate paychecks
int main( )
{ float hours, pay, rate,
for (int count=0; count<3; count++)
{
cout << "enter hours and rate: ";
cin >> hours >> rate;
pay = rate * hours;
cout << "pay is " << pay;
}
}
17
Agenda
while loops
for loops 
designing for loops
user-controlled loops
debugging loops
18
An example for loop
for (int i = 10 ; i > 0 ; i=i-1 )
cout <<i << " ";
cout << "blast off!"<<endl;
The Above code Displays:
10 9 8 7 6 5 4 3 2 1 blast off!
19
Your Turn
1) What does this code display?
for (int i = 20 ; i <50 ; i=i+5 )
cout <<i << " ";
More practice online, see Lec7_ForLoops
20
Pitfalls in for loops
Header “out of sync”
a) for (int i=1; i> 10 ; i++ )
cout << i << " ";
b) for (int i=5; i> 0 ; i++ )
cout << i << " ";
Ending header w/ a semicolon:
for (int i=5; i> 0 ; i-- );
cout << i << " ";
21
Sum the numbers from 1 to n
int main()
{
int n = 8, i, sum = 0;
for (i=0; i<=n; i++)
sum = sum + i;
cout<<"Sum is : "<<sum<<endl;
}
22
Find average of 4 input integers
// avginpt.cpp
Find average of 4 integers.
int main()
{
int i, number, sum;
sum = 0;
for (i=1; i<=4; i+=1)
{
cout << "Enter number: ";
cin >> number;
sum += number;
}
cout << "Average = " << sum/4.0 << endl;
}
23
Agenda
while loops
for loops
designing for loops 
user-controlled loops
debugging loops
24
General Design of for loops that
process groups of data
Initialize any variables that sum, count
for (int i=1; i< ???; i++)
{
ask for data and input it (cout-cin)
process and display input data
}
Output any sums, or tallies
25
You can let the user enter loop
control variables
// Modified avginpt.cpp Ask user how many ints
int main()
{
int i, number, sum=0, numData;
cout<<“How many data points?”<<endl;
cin>>numData;
for (i=1; i<=numData; i+=1)
{
cout << "Enter number: ";
cin >> number;
sum += number;
}
cout << "Average = " << sum/numData << endl;
}
26
Other for loop possibilities
Sometimes, you can use the loop counter as your
data. For example, sum the squares of the numbers 1
to 100 (see sumsquares.cpp)
int i;
long sum = 0;
for (i=1; i<=100; i++)
sum = sum + i*i;
cout << "Sum of first 100 squares="
<< sum <<endl;
27
Display table of integers and their squares.
int j;
// Display the headings for the table.
cout << "j
Square" << endl;
for ( j = 1; j <= 5; j=j+1)
cout << j << "
" << j * j <<endl;
j
1
2
3
4
5
Square
1
4
9
16
25
OUTPUT
Same idea for Problem 9
tempTable.cpp
28
Finding the largest…
float num, max=0; // make a variable to hold max
cin>>num;
Core idea
Compare num with max…
if (num>max)
// if num is bigger
max=num;
// max get’s num’s value
29
Finding the largest…put in a loop
int i, num, max_so_far;
cout << "Enter number: ";
cin >> max_so_far;
See maxof5.cpp
for (i=2; i<=5; i+=1)
Use this idea
{
on problem 16
statistics.cpp
cout << "Enter number: ";
cin >> num;
if (num > max_so_far)
max_so_far = num;
} // end for
cout << "The max " << max_so_far << endl;
30
Agenda
while loops
for loops
designing for loops
user-controlled loops 
debugging loops
31
User Controlled Loop Concept
Read first data set
while (data is “Good”) (not a sentinel)
calc result for last data
display result
get another data set
32
User Controlled Loop Code
// CALCPAY.CPP A program to calculate paychecks
int main( )
{ float hours, pay, rate;
cout << "enter hours and rate, -1 -1 to stop: ";
cin >> hours >> rate;
// get first data set
while(hours>0)
// is data OK
{
pay = rate * hours;
// process last data set
cout << "pay is " << pay;
cin >> hours >> rate;
// get next data set
}
}
33
What is a Sentinel?
Data that is clearly not valid—phony
Hours worked = -1
Radius = -1
HighTemperature= – 1000
JellyBeans=-1
34
Sum any number of values (findsum1.cpp)
int sum, num;
sum = 0;
cout << "Enter number (negative to quit): ";
cin >> num;
while (num >= 0)
{
sum = sum + num;
cout << "Enter number (negative to quit): ";
cin >> num;
}
cout << "Sum = " << sum << endl;
35
Another User Control Variation (findsum2.cpp)
int sum, num;
char ans;
sum = 0;
do {
cout << "Enter number: ";
cin >> num;
sum = sum + num;
cout << " Continue? (y/n) ";
cin >> ans;
}
while (ans != 'n' && ans != 'N');
cout << "Sum = " << sum << endl;
Try both, which is
better?
36
While vs Do-While Loops:
notice the differences
Post.cpp
Pre.cpp
x = 99;
do {
cout << x << endl;
x++;
}
while (x < 0);
x = 99;
while (x < 0)
{
cout << x << endl;
x++;
}
37
Agenda
while loops
for loops
designing for loops
do while loops and user-controlled loops
debugging loops 
38
Debugging Loops
Reread Program
Trace program, 1 of 3 ways
Insert extra cout statements
• Show changing variables as loop progresses
Use built in Debugger
• Let you step thru code 1 line at a time while executing it
Hand trace
• Valuable skill, no computer required
39
Try hand tracing trace1.cpp
using inputs 5, 30, 10, 40, 15, 29
for (i=1; i<=3; i++)
{
cout << "Enter a number: ";
cin >> num1;
num2 = num1 + 2;
num1--;
cout << num1 << " " << num2 << endl;
cout << "Enter a number: ";
cin >> num2;
} // end for
cout << num1 << " " << num2 << endl;
40
Try tracing trace2.cpp (no input)
n = 1;
sum = 0;
do {
sum = sum + n*n;
n = n + 2;
}
while (n < 8);
cout << "Sum = " << sum << endl;
41
Download