29
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

REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

Embed Size (px)

Citation preview

Page 1: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 2: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 3: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

Structuring Input Loops

3

Common repetition structures:

counter-controlled sentinel-controlled end-of-data controlled

Page 4: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

Counter-controlled Repetition Structure

input counter

for count=1 to counterinput 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

Page 5: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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 markadd the mark to the running sumincrement 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

Page 6: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 7: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 8: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 9: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

Sentinel-controlled Repetition Structure

input data value

while data value ! = sentinel valuedo 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

Page 10: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 11: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

• 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

Page 12: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 13: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

// 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 <iomanip>

You need to check that user entered at least one mark, also to avoid division by zero

Page 14: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 15: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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.

Page 16: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 17: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 18: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

Page 19: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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

19

Notice 2 closing parenthesis

Page 20: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

// 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 <iomanip>

You need to check that user entered at least one mark, also to avoid division by zero

Page 21: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

Enter exam marks separated by white spaces: 75 94 97 88 70 64 83 89

Class average is 82.50

21

Page 22: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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 2for( int i=1; i<=10; i++)

cout<< “2 x “<<i<<“= “<<2*i<<endl;

//leave empty linecout<<“\n”;

//compute powers of 2, need to include <cmath> for powfor(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

Page 23: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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 i nfact5 15 5 55 4 205 3 605 2 1205 1

5! = 120

Page 24: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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 mwhile(n > 0){

nfact = nfact*n;n--;

}//use m variable to display original n valuecout << m<< “! = " << nfact << endl;

5! = 120

nnfact

15 54 203 602 1203 1200

Page 25: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

• 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 01 0 11 1 22 0 32 1 43 0 53 1 6

25

outer for loopinner for loop

Page 26: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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 output0 01 Goodbye

Page 27: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

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;

i output0 012 234 45 6 67 8 89 10 1011 Goodbye

Page 28: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

28

The break statementPractice: 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.

Page 29: REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled

29

The continue statementPractice: 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.