Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Structures Repetition or Iteration or Looping Part II.

Similar presentations


Presentation on theme: "Control Structures Repetition or Iteration or Looping Part II."— Presentation transcript:

1

2 Control Structures Repetition or Iteration or Looping Part II

3 Loop Controls Counter-controlled loops repeat a specific number of times (You can calculate the number of iterations.) Use a for loop Event-controlled loops repeats until something happens in the loop body to change the evaluation of the expression

4 Sentinels These are used in event-controlled loops. The loop can be executed any number of times. It stops only when a specific event occurs. A sentinal is a unique value that can be used to signal an event. This value cannot be valid for normal processing, I.e., -1 may be valid for degrees farenheit, but not for test scores. * Test Scores 67, 89, 94, 82, -1

5 Running Totals count =1 //read or assign total = 0; while (count <=4) { } cout > num; total = total + num; cout “The total is now “ << total << endl; count++; *

6 total = 0; num = 0; num != 999 while ( num != 999 ) { total = total + num; cout “\nThe total is now “ << total; cout << “Enter a number: “; cin >> num; // user causes the event } Sentinal Value – An input event 999 must not be valid in this context

7 flag = 1; flag while ( flag ) { total = total + num; cout “\nThe total is now “ << total; cout << “Enter a number: “; cin >> num; if( num > 999) flag = 0; } Flag Example A flag is any variable whose value indicates program status

8 count <=4 while ( count <=4 ) { total = total + num; cout “\nThe total is now “ << total; cout << “Enter a number: “; cin >> num;count++; } Sentinel Example cout << “\nEnter a number: “; cin >> num; } primary read num != 999 * *

9 Average – again, using while int num, count = 1; float average, total = 0.0; cout << "Enter a number: "; // priming read cin >> num; while (count <= 4) { total = total + num; // accumulating a total cout << “The total is “ << total << ‘\n’; cout << "Enter a number: "; cin >> num; count++;// how many times ? } // Can you see the weakness in this program? count--;// WHY? average = total / count; cout << "\nThe average is " << average << '\n';

10 Average – again, using for int num, count; float average, total = 0.0; for (count = 1; count <= 4; count++) { cout << "Enter a number: "; cin >> num; total = total + num; // accumulating a total cout << “The total is ” << total << ‘\n’; }// how many times ? count--;// WHY? average = total / count; cout << "\nThe average is " << average << '\n';

11 break and continue Statements Interrupt the normal flow of control. break causes an exit from innermost enclosing loop or switch statement. continue cause current iteration of a loop to stop and the next iteration to begin immediately. continue may only be used in while, for, and do loops. * * *

12 The break Statement int j =50; 1 while (j < 80) 2 { 3 j += 10; 4 if (j == 70) 5 break; 6 cout << “j is “ << j<< ‘\n’; 7 } 8 cout << “We are out of the loop.\n”;

13 The break Statement Output j is 60 We are out of the loop. Sequence of execution: 1 2 3 4 6 7 1 2 3 4 5 8

14 The continue Statement int j =50; continue 1 while (j < 80) 2 { 3 j += 10; 4 if (j == 70) 5 continue; 6 cout << “j is “ << j<< ‘\n’; 7 } 8 cout << “We are out of the loop.\n”;

15 The continue Statement Output j is 60 j is 80 We are out of the loop. Sequence of execution: 1 2 3 4 6 7 1 2 3 4 5 1 2 3 4 6 7 1 8

16 break and continue while ( - - - ) { statement-1; if( - - - )continue statement-2; } statement-3; while ( - - - ) { statement-1; if( - - - )break statement-2; } statement-3; *

17 The do Statement Variant of the while statement Syntax do while do statement while (expression); next statement

18 The do Statement Exit the do 0 or False loop Test the expression statements to execute 1 or True Always executes at least once

19 do Example: do { cout > age; if (age <=0) cout << “Invalid age.\n”; while (age <=0) else cout << "DO SOMETHING\n"; } while (age <=0) ; do Statments

20 cout << "Enter your age: "; cin >> age; while while (age <= 0) { if (age <=0) { cout << "Invalid age.\n"; cout << "Enter your age: "; cin >> age; } else cout << "DO SOMETHING\n"; } do vs. while

21 sum = 0; count = 1; do {I/O sum += count; count++; } while (count <=n); sum = 0; count = 1; I/O // priming read while (count <=n) { sum += count; count++;I/O } do vs. while Make sure that count and sum are correct

22 do  while  for sum = 0; cnt = 1; do { sum += cnt; cnt++; } while (cnt <=n); sum = 0; cnt = 1; while (cnt <=n) { sum += cnt; cnt++; } sum = 0; cnt = 1 for (cnt = 1; cnt <= n; cnt++) sum += cnt; // what if… // cin >> n; // read a zero?

23 Guidelines for choosing: + If simple count-controlled, use a for. + If event-controlled and body is executed at least once, use do. + If event-controlled and nothing is known about the first execution, use while. + When in doubt use while.

24 Validity Checking Validity checking or data validation is a way of notifying the user of invalid data. You should validate every input value for which any restrictions apply. *

25 A Sample Problem Write a program that accepts a user determined number of experiments with a user determined number of scores for each experiment. It displays the average of the scores for each experiment.

26 How many experiments are there? 2 How many scores are there? 3 Enter the scores for experiment 1: Enter result of test 1 : 98 Enter result of test 1 : 56 Enter result of test 1 : 34 The average for experiment 1 is 63 How many scores are there? 4 Enter the scores for experiment 2: Enter result of test 2 : 21 Enter result of test 2 : 32 Enter result of test 2 : 16 Enter result of test 2 : 29 The average for experiment 2 is 25 Press any key to continue

27 Plan for Sample Program read # experiments for read # scores for read individual scores increment total average scores display average * * *

28 {int exper, test, howmany1, howmany2; double total, score, avg; cout << "How many experiments are there? "; cin >> howmany1; for (exper =1; exper<=howmany1; exper=exper +1) {cout << "How many scores are there? "; {cout << "How many scores are there? "; cin >> howmany2; cin >> howmany2; cout << "\tEnter the scores for experiment " cout << "\tEnter the scores for experiment " << exper <<": \n"; total = 0; << exper <<": \n"; total = 0; for (test = 1; test <=howmany2; test = test +1) for (test = 1; test <=howmany2; test = test +1) {cout << "Enter result of test " << test <<" : "; {cout << "Enter result of test " << test <<" : "; cin >> score; cin >> score; total = total + score; } total = total + score; } avg = total/(test-1); avg = total/(test-1); cout << "The average for experiment " << exper cout << "The average for experiment " << exper << " is " << setprecision(2) << avg << "\n\n"; << " is " << setprecision(2) << avg << "\n\n"; } } }

29 Reverse_digits example Write a program to reverse the digits of a positive integer. For example if the number is 8735, the displayed number should be 5378. * Hint: Use a do statement and continually strip off and display the units digit of the number (number % 10). After the units digit is displayed, dividing the number by 10 strips off the current units digit and sets up number for the next iteration. Thus, (8735 % 10) is 5 and (8735 / 10) is 873. The do statement executes until number is zero.

30 Palindrome Example A palindrome is a phrase (number or text) that reads the same backwards as forwards. For example, the following are palindromes: 12321, madam i'm adam. Write a program that reads a five-digit integer and determines whether or not it is a palindrome. Ask the user if another possible palindrome is to be entered.

31 The End the end

32 Common Errors Using = in place of = = Placing a ; after the for’s parentheses or after a while condition – before the loop statements. Using a, to separate items in a for expression - you need a ; Omitting the final ; in the do statement

33 Common Errors != versus == This changes the logic, be especially careful when used with && or || ( ) && ( ) && ( ) versus ( ) || ( ) || ( ) } note this

34 Debugging Syntax errors vs. Logic error Prevention - plan first! Valuation tables: expected output Display intermediate values C++ Debugger *


Download ppt "Control Structures Repetition or Iteration or Looping Part II."

Similar presentations


Ads by Google