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

Slides:



Advertisements
Similar presentations
Chapter 04 (Part III) Control Statements: Part I.
Advertisements

Computer Science 1620 Loops.
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
LOOPING do { } while ( ) for (I = 0; I < 5; I++) { } while ( ) { }
Chapter 5: Control Structures II (Repetition)
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
Control Structures in C++ while, do/while, for switch, break, continue.
Chapter 5: Control Structures II (Repetition)
What is the out put #include using namespace std; void main() { int i; for(i=1;i
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Control Structures Outline -Introduction -Algorithms -Pseudocode -Control Structures -if Selection Structure.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
1 Lecture 3 Control Structures else/if and while.
Lecture 5: Stopping with a Sentinel. Using a Sentinel Problem Develop a class-averaging program that will process an arbitrary number of grades each time.
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (while) Outline 3.7The While Repetition.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Introduction to Computer Programming
REPETITION CONTROL STRUCTURE
while Repetition Structure
Engineering Problem Solving with C++, Etter/Ingber
Week 4 – Repetition Structures / Loops
Control Statements Kingdom of Saudi Arabia
Lecture 4B More Repetition Richard Gesick
Let’s all Repeat Together
2.6 The if/else Selection Structure
Chapter 5: Control Structures II (Repetition)
EPSII 59:006 Spring 2004.
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

Enter exam marks separated by white spaces: Class average is

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 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 ! = 120

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

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 outer for loop inner for loop

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

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