Download presentation
Presentation is loading. Please wait.
Published byCecily Lang Modified over 9 years ago
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 1
2
Structuring Input Loops 2 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 3 Common repetition structures: counter-controlled sentinel-controlled end-of-data controlled
4
Counter-controlled Repetition Structure input counter for count=1 to counter input data value do something with data value increment count 4 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 Indicates data size, i.e. number of repetitions required Loop count
5
Formulating Algorithms (Counter-Controlled Repetition) 5 Problem: Compute Average Mark for Class of n students 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 Next C++ Program n is used as counter controlling the repetition Note that average value is computed outside the loop, after the loop completes
6
// Class average program with counter-controlled repetition. #include 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; return 0; // 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 input data value while data value ! = sentinel value do something with data value input next data value end while 9 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
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
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” Formulating Algorithms (Sentinel-Controlled Repetition) You must check count is not zero before division Need to compute count and must be initialised to zero You must increment count Notice the positions of input/read data just before the loop and at the very end of the loop
12
// Class average program with sentinel-controlled repetition. #include 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
// 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; return 0; // indicate program ended successfully } 13 setprecision(2) & fixed print two digits past decimal point (rounded to fit precision). Programs that use this must include You need to check that user entered at least one mark, also to avoid division by zero
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 15 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.
16
input data value while end-of-file is not true //Do something with input data input next data value end while eof()-controlled Repetition Structure 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
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” Formulating Algorithms (eof()-Controlled Repetition) 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 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 19 Notice 2 closing parenthesis
20
// 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; return 0; // indicate program ended successfully } 20 setprecision(2) & fixed print two digits past decimal point (rounded to fit precision). Programs that use this must include You need to check that user entered at least one mark, also to avoid division by zero
21
Enter exam marks separated by white spaces: 75 94 97 88 70 64 83 89 Class average is 82.50 21
22
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. for Loop (Revisited.) //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 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
23 Practice -factorial ! 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 //Trace program for n=5? //Write an alternate solution. Loop Trace: n infact 5 1 5 5 5 5 4 20 5 3 60 5 2 120 5 1 5! = 120
24
24 Practice -factorial ! while loop Implementation: //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 nnfact 1 5 4 20 3 60 2 120 1 120 0
25
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 Nested for Loops int count=0; for (int i= 1; i<=3; i++) for(int j=0; j<2; ++j) { count++; cout<<count<<endl; } Loop Trace: i j count 0 1 0 1 1 1 2 2 0 3 2 1 4 3 0 5 3 1 6 25 outer for loop inner for loop
26
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: ioutput0 1Goodbye
27
27 The continue statement continue; –Jumps to the next iteration of the loop, skipping any remaining statements in the loop 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; ioutput0 1 2 3 4 5 6 7 8 9 10 11 Goodbye
28
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.
29
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.