1 / 29

REPETITION STATEMENTS - Part2

REPETITION STATEMENTS - Part2. Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled Repetition Structure The break Statement The continue Statement. Structuring Input Loops.

Download Presentation

REPETITION STATEMENTS - Part2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled Repetition Structure The break Statement The continue Statement

  2. Structuring Input Loops Repetition is useful when inputting different set of data for the same information/variable either from the keyboard or from a file while performing the same action (s). • Checking weather level for a set of cities • Computing GPA for a set of students • Checking gas level for a set of wellheads

  3. Structuring Input Loops • Common repetition structures: • counter-controlled • sentinel-controlled • end-of-data controlled 3

  4. Counter-controlled Repetition Structure Indicates data size, i.e. number of repetitions required • Definite repetition: number of repetitions known • Loop is repeated until the value of the counter is reached • the value of the counter is known and often read from the keyboard and stored in the counter • The for loop implementation is commonly used for counter-controlled repetition Loop count input counter for count=1 to counter input data value do something with data value increment count

  5. Formulating Algorithms (Counter-Controlled Repetition) Problem: Compute Average Mark for Class of n students n is used as counter controlling the repetition • Algorithm in Pseudocode: • Initialize sum to zero • Input number of marks into n • for count=1 to n input the next mark add the mark to the running sum increment count • Compute average as sum/n • Print the class average Note that average value is computed outside the loop, after the loop completes • Next C++ Program 5

  6. // Class average program with counter-controlled repetition. #include <iostream> using namespace std; // function main begins program execution int main() { int n; // number of marks as a counter int sum; // sum of marks input by user int mark; // mark value int average; // average of marks //initialization phase sum = 0; // initialize sum //Prompt for the number of marks cout<< “Enter the number of marks to be read: “; cin>>n; 6

  7. for (int count =1; count <= n; count++ ) // loop n times { cout << "Enter mark (0-100): "; // prompt for input cin >> mark; // read mark from user sum = sum + mark; // add mark to sum } average = sum / n; // integer division cout << "Class average is " << average << endl; return0; // indicate program ended successfully } // end function main n determines the number of required loop iterations/passes. When the loop count exceeds n loop terminates. 7

  8. Enter mark (0-100): 98 Enter mark (0-100): 76 Enter mark (0-100): 71 Enter mark (0-100): 87 Enter mark (0-100): 83 Enter mark (0-100): 90 Enter mark (0-100): 57 Enter mark (0-100): 79 Enter mark (0-100): 82 Enter mark (0-100): 94 Class average is 81 8

  9. Sentinel-controlled Repetition Structure • Unknown number of iterations/repetitions • How will program know when to end the loop? • Loop ends when a special data value, called sentinel value is read • Sentinel value is usually chosen as a value that does not occur naturally in the input data sets 9 input data value while data value ! = sentinel value do something with data value input next data value end while

  10. Sentinel-Controlled Repetition • The class average mark problem - Different context • Unknown number of students! • How to stop program or data entry? • Use Sentinel value: ask the user to enter Sentinel value when finish entering data: • Loop ends when sentinel is read • Sentinel chosen so it cannot be confused with regular marks, e.g. -1 ( or any negative mark value) 10

  11. Formulating Algorithms (Sentinel-Controlled Repetition) • Class Average - Pseudocode Algorithm: Initialize sum to zero Initialize count to zero Input the first mark (possibly the sentinel) While current mark is not the sentinel Add this mark into the running sum Increment mark count Input the next mark (possibly the sentinel) If the count is not equal to zero Set the average to the sum divided by count Print the average Else Print “No marks were entered” Need to compute count and must be initialised to zero Notice the positions of input/read data just before the loop and at the very end of the loop You must increment count You must check count is not zero before division

  12. // Class average program with sentinel-controlled repetition. #include <iostream> #include <iomanip> using namespace std; int main() { // Declaration and initialization phase double mark, sum(0), average ; int count (0); // loop index used to count number of marks entered // processing phase // get first mark from user cout << "Enter mark, -1 to end: "; // prompt for input cin >> mark; // read mark from user // loop until sentinel value read from user while ( mark !=-1) { sum = sum + mark; // add mark to total count++; // increment count, the loop index cout << "Enter mark, -1 to end: "; // prompt for input cin >> mark; // read next mark } // end while 12

  13. You need to check that user entered at least one mark, also to avoid division by zero // if user entered at least one grade ... if (count >0 ) { // calculate average of all marks entered average = sum / count; // display average with two digits of precision cout << "Class average is " << fixed<<setprecision( 2 )<< average << endl; } // end if part of if/else else// if no marks were entered, output appropriate message cout << "No marks were entered" << endl; return0; // indicate program ended successfully } setprecision(2) & fixed print two digits past decimal point (rounded to fit precision). Programs that use this must include <iomanip> 13

  14. Enter mark, -1 to end: 75 • Enter mark, -1 to end: 94 • Enter mark, -1 to end: 97 • Enter mark, -1 to end: 88 • Enter mark, -1 to end: 70 • Enter mark, -1 to end: 64 • Enter mark, -1 to end: 83 • Enter mark, -1 to end: 89 • Enter mark, -1 to end: -1 • Class average is 82.50 14

  15. eof()-controlled Repetition Structure • Unknown/unspecified number of iterations/repetitions • Execution of loop terminates when end of data is reached • End of data can be checked from the value of the function eof(). • When reading from the keyboard, eof() becomes true if the user presses (ctrl+z) twice. 15

  16. eof()-controlled Repetition Structure • input data value • while end-of-file is not true • //Do something with input data • input next data value • end while 16

  17. eof()-Controlled Repetition • Class average problem: Develop a class-averaging program that will process unspecified number of marks • unspecified number of marks indicates unknown number of marks, i.e., • Use eof() to test end of data entry. • eof() will become true once the user indicates end of entry by pressing (ctrl+z) twice. 17

  18. Formulating Algorithms (eof()-Controlled Repetition) Class Average - Pseudocode Refinement: Initialize sum to zero Initialize mark count to zero Input the first mark While not end of data reached Add this mark into the running sum Increment mark count Input the next mark If the count is not equal to zero Set the average to the sum divided by count Print the average Else Print “No marks were entered” Need to compute count and must be initialised to zero Need to check count not zero before division

  19. // Class average program with eof()-controlled repetition. #include <iostream> #include <iomanip> using namespace std; int main() { // Declaration and initialization phase double mark, sum(0), average ; int count (0); // loop index used to count number of marks entered // processing phase // get first mark from user cout << "Enter exam marks separated by white spaces: “<<endl; // prompt for input cin >> mark; // read mark from user // loop until cin.eof() becomes true while (!cin.eof()) { sum = sum + mark; // add mark to total count++; // increment count, the loop index cin >> mark; // read next mark } // end while Notice 2 closing parenthesis 19

  20. You need to check that user entered at least one mark, also to avoid division by zero setprecision(2) & fixed print two digits past decimal point (rounded to fit precision). Programs that use this must include <iomanip> // termination phase // if user entered at least one grade ... if (count != 0 ) { // calculate average of all marks entered average = sum / count; // display average with two digits of precision cout << “\nClass average is " << fixed<<setprecision( 2 ) << average << endl; } // end if part of if/else else// if no marks were entered, output appropriate message cout << “\nNo marks were entered" << endl; return0; // indicate program ended successfully } 20

  21. Enter exam marks separated by white spaces: • 75 94 97 88 70 64 83 89 • Class average is 82.50 21

  22. for Loop(Revisited.) When using two for loops with the same variable in the same program, declare the variable only once either in the first loop or before both loops in the declaration. • //compute multiples of 2 • for( int i=1; i<=10; i++) • cout<< “2 x “<<i<<“= “<<2*i<<endl; • //leave empty line • cout<<“\n”; • //compute powers of 2, need to include <cmath> for pow • for(i=0; i<=10; i++) • cout<<“pow(2,”<<i<<“) = “<<pow(2,i)<<endl; Notice: You should not write int here because i is already declared in previous for loop. 22

  23. Practice -factorial! Loop Trace: n i nfact 5 1 5 5 5 5 4 20 5 3 60 5 2 120 5 1 • for-loop Implementation: int nfact=1, n; cout << "enter positive integer "; cin >> n; for(int i=n; i>1;i--) { nfact = nfact*i; } cout << n<< “! = " << nfact << endl 5! = 120 //Trace program for n=5? //Write an alternate solution. 23

  24. Practice -factorial! • while loop Implementation: • n nfact • 1 • 5 • 4 20 • 3 60 • 120 • 120 • 0 //calculates n! //uses n as a loop index int nfact=1, n; cout << “enter positive integer “; cin >> n; int m=n; //store original n value in m while(n > 0) { nfact = nfact*n; n--; } //use m variable to display original n value cout << m<< “! = " << nfact << endl; 5! = 120 24

  25. Nested for Loops • for loop within another for loop • Use different loop indexes (common: i, j, k), others are possible • Inner loop is fully executed in each outer loop iteration Loop Trace: i j count 0 1 0 1 1 1 2 2 0 3 2 1 4 3 0 5 3 1 6 • int count=0; • for (int i= 1; i<=3; i++) • for(int j=0; j<2; ++j) • { • count++; • cout<<count<<endl; • } inner for loop outer for loop 25

  26. The break statement break; terminates loop execution continues with the first statement following the loop Example1: What is the output? for (int i=0; i<=10; ++i) { if(i%2==1) break; cout << i << endl; } cout<<“Goodbye…\n”; return 0; Program Trace: i output 0 0 1 Goodbye 26

  27. The continue statement continue; Jumps to the next iteration of the loop, skipping any remaining statements in the loop • i output • 0 0 • 1 • 2 • 4 • 6 • 8 • 10 • Goodbye Example1: What is the output? for (int i=0; i<=10; ++i) { if(i%2==1) continue; cout << i << endl; } cout<<“Goodbye…\n”; return 0; 27

  28. The break statement Practice: Run and test the output of this code segment? double x, sum=0; for (int k=1; k<=20; ++k){ cout <<“Enter value of x: “; cin>x; if (x > 10.0) break; sum+=x; } cout<<“sum = “<<sum<<endl; Note: The break statement will exit the loop if a single x value >10 is read. 28

  29. The continue statement Practice: Run and test the output of this code segment? double x, sum=0; for (int k=1; k<=20; ++k) { cout <<“Enter value of x: “; cin>x; if (x > 10.0) continue; sum+=x; } cout<<“sum = “<<sum<<endl; Note: The continue statement will skip remaining statements and jump to next loop iteration/pass. 29

More Related