Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Three C++ Looping Statements Chapter 7 CSIS 10A."— Presentation transcript:

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

2 2 Agenda while loops  for loops designing for loops user-controlled loops debugging loops

3 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

4 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++; cout << count; Summing: sum=0; sum = sum + 8; sum = sum + 3; sum += 15; cout << sum; Initialization is key

5 5 while-loop, fixed step n < = 3 Display n Add 1 to n true false Flowchart: while-loop n = 1; Display done

6 6 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

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

8 8 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?

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

10 10 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) { 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!

11 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

12 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…

13 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

14 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

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

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

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

18 18 Agenda while loops for loops  designing for loops user-controlled loops debugging loops

19 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!

20 20 Your Turn 1) What does this code display? for (int i = 20 ; i <50 ; i=i+5 ) cout <<i << " ";

21 21 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 << " "; Do Problems 1 - 4

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

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

24 24 Agenda while loops for loops designing for loops  user-controlled loops debugging loops

25 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

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

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

28 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 Square 1 2 4 3 9 4 16 5 25 See problem 7 Same idea for Problem 12 OUTPUT

29 29 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

30 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

31 31 Agenda while loops for loops designing for loops user-controlled loops  debugging loops Do Problems 5 - 8

32 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

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

34 34 What is a Sentinel? Data that is clearly not valid—phony Hours worked = -1 Radius = -1 HighTemperature= – 1000 JellyBeans=-1

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

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

37 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?

38 38 While vs Do-While Loops: notice the differences Post.cppPre.cpp x = 99; do { cout << x << endl; x++; } while (x < 0); x = 99; while (x < 0) { cout << x << endl; x++; }

39 39 Agenda while loops for loops designing for loops do while loops and user-controlled loops debugging loops 

40 40 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

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

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


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

Similar presentations


Ads by Google