1 Three C++ Looping Statements Chapter 7 CSIS 10A.

42
1 Three C++ Looping Statements Chapter 7 CSIS 10A

Transcript of 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

Page 1: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

1

Three C++ Looping Statements

Chapter 7CSIS 10A

Page 2: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

2

Agenda

while loops

for loops

designing for loops

user-controlled loops

debugging loops

Page 3: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

3

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

Page 4: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

4

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;

Initialization is key

Page 5: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

5

while-loop, fixed step

n < = 3 Display n

Add 1 to n

true

false

Flowchart: while-loop

n = 1;

Display done

Page 6: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

6

While Loop StatementThe previous flowchart illustrates a while-loop:

n = 1;

while (n <= 3) { cout << n << “ ”; n = n + 1; }

cout<< done <<endl;

Output: 1 2 3 done

Page 7: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

7

while Loop Syntax

while (boolean expression is true) { statements to repeat ; }

Semi-colons are used only to end the statementswithin the loop (not after boolean expression)

while (boolean expression is true) statement to repeat;

Page 8: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

8

Your Turn

Can youShow 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?

Page 9: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

9

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;

Page 10: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

10

Infinite LoopsLoops that never stop are infinite loopsThe loop body should contain a line that willeventually cause the boolean expression to become falseExample: Print the odd numbers less than 12 x = 1; while (x < 12) { cout << x << endl; x = x – 2; }In this loop, make x larger: x=x+2;

Hit Ctrl-C to abort

See silent.cpp for a silent infinite loop!

Page 11: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

11

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

Page 12: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

12

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…

Page 13: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

13

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

Page 14: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

14

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;

}}

PROBLEM 3

Page 15: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

15

Step Controlled Loop using While

k=0; // initialize counter

while(k<3) // check counter

{

STATEMENTS TO REPEAT;

k=k+1; // add 1 to counter

}

Page 16: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

16

A Better Step Controlled Loop uses For

for( k=0; k<3; k=k+1 )

{

STATEMENTS TO REPEAT;

}

More compact, easy to read, and works exactly like the while loop (same flowchart)

Or k++

Page 17: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

17

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;

}}

Page 18: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

18

Agenda

while loops

for loops

designing for loops

user-controlled loops

debugging loops

Page 19: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

19

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!

Page 20: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

20

Your Turn

1) What does this code display?

for (int i = 20 ; i <50 ; i=i+5 )

cout <<i << " ";

Page 21: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

21

Pitfalls in for loopsHeader “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 << " ";

Do Problems 1 - 4

Page 22: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

22

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;

}

Page 23: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

23

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;}

Page 24: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

24

Agenda

while loops

for loops

designing for loops user-controlled loops

debugging loops

Page 25: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

25

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

Page 26: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

26

You can let the user enter loop control variables

// Modified avginpt.cpp Ask user how many intsint 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;}

Page 27: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

27

Other for loop possibilitiesSometimes, 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;

Page 28: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

28

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 Square1 12 43 94 165 25

See problem 7Same idea for Problem 12

OUTPUT

Page 29: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

29

Finding the largest…

float num, max=0; // make a variable to hold max

cin>>num;

Core ideaCompare num with max…

if (num>max) // if num is bigger

max=num; // max get’s num’s value

Page 30: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

30

Finding the largest…put in a loop

int i, num, max_so_far; cout << "Enter number: "; cin >> max_so_far; for (i=2; i<=5; i+=1) { cout << "Enter number: "; cin >> num; if (num > max_so_far) max_so_far = num; } // end for cout << "The max " << max_so_far << endl;

Use this idea on problem 8

Page 31: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

31

Agenda

while loops

for loops

designing for loops

user-controlled loops debugging loops

Do Problems 5 - 8

Page 32: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

32

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

Page 33: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

33

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 setwhile(hours>0) // is data OK{

pay = rate * hours; // process last data setcout << "pay is " << pay;cin >> hours >> rate; // get next data set

}}

Page 34: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

34

What is a Sentinel?

Data that is clearly not valid—phonyHours worked = -1

Radius = -1

HighTemperature= – 1000

JellyBeans=-1

Page 35: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

35

Sum any number of values

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;

Page 36: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

36

Average any number of values

float sum=0, num, avg; cout << "Enter number (negative to quit): "; cin >> num; while (num >= 0) { sum = sum + num;

k = k + 1; cout << "Enter number (negative to quit): "; cin >> num; } cout << “Avg = " << sum/k << endl;

Page 37: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

37

Another User Control Variation

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?

Page 38: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

38

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++;

}

Page 39: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

39

Agenda

while loops

for loops

designing for loops

do while loops and user-controlled loops

debugging loops

Page 40: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

40

Debugging LoopsReread Program

Trace program, 1 of 3 waysInsert 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

Page 41: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

41

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;

Page 42: 1 Three C++ Looping Statements Chapter 7 CSIS 10A.

42

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;