680 likes | 1.33k Views
Basic Loop Structures. Loops repeat execution of an instruction set Three repetition structures: while, for, do-while Three common elements Test condition controls repetition Statement initializes state of test condition Internal statement terminates loop
E N D
Basic Loop Structures • Loops repeat execution of an instruction set • Three repetition structures: while, for, do-while • Three common elements • Test condition controls repetition • Statement initializes state of test condition • Internal statement terminates loop • Syntax variations around placement/type of test Object-Oriented Program Development Using C++
Pretest and Posttest Loops • Pretest (entrance-controlled) loop • Condition tested before loop statements executed • Examples: while and for statements • Posttest (exit-controlled) loop • Termination condition tested at end of loop • Loop guaranteed to execute at least once • Example: do-while • Infinite loop: results from improper update of test Object-Oriented Program Development Using C++
Figure 6-1 A Pretest Loop Object-Oriented Program Development Using C++
Figure 6-2 A Posttest Loop Object-Oriented Program Development Using C++
Fixed-Count versus Variable-Condition Loops • Fixed-count loop: condition tracks number of repetitions • Variable condition loop: test depends on changing variable • All C++ repetition structures adaptable to either type Object-Oriented Program Development Using C++
while Loops • Example of while statement: int count = 1; // initialize count while (count <= 10){ cout << count << endl; count++; // increment count } • Loop turns around value of count • Termination value: count after increment to 11 Object-Oriented Program Development Using C++
Figure 6-3 Structure of a while Loop Object-Oriented Program Development Using C++
Interactive while Loops • while statement promotes interactivity • Include interactive prompts and cin statement • Sample program • Enters and echo-prints four numbers • Utilizes accumulation statement • Totals input, computes average, outputs result • Terminates after fixed count Object-Oriented Program Development Using C++
Figure 6-4 Flow of Control for Program 6-5 Object-Oriented Program Development Using C++
Figure 6-5 Accepting and Adding a Number to a Total Object-Oriented Program Development Using C++
Sentinels • Sentinels • Values signal start or end of series • May or may not share data type of input • Code fragment: cout << "\nTo stop entering numbers, type in any " << "number greater than 100" << endl; while (number <= MAX_COUNT) • number value greater than 100 terminates loop Object-Oriented Program Development Using C++
break and continue Statements • break statement • Forces exit from repetition or switch statement • Syntax: break; • Most appropriately used in switch statement • continue statement • Short circuit to next iteration • Syntax: continue; • Applies to while, do-while, and for structures Object-Oriented Program Development Using C++
The null Statement • null statement: consists of a semicolon ( ; ) • Typical use: repetition structure without loop body • Example • for (int count = 1; count <= pow(10,7) ; count++); • Time delay loop requires no explicit action Object-Oriented Program Development Using C++
for Loops • for loop: while functionality with alternate syntax • Syntax template: for (initializing list; expression; altering list){ statement(s); } • Three components between parentheses optional • Initialization, test, and update conveniently clustered • Commas separate additional items added to component Object-Oriented Program Development Using C++
Figure 6-7 for Loop Control Object-Oriented Program Development Using C++
Figure 6-8 Simplified for Loop Flowchart Object-Oriented Program Development Using C++
Nested Loops • Nested loops: loops within other control structures • Add dimensionality to data • Code fragment for (int i = 1; i <= 10; i++){ // start outer loop for (int j = 1; j <=10; j++){ // start inner loop cout << asterisk << space; } // end inner loop } // end outer loop • Inner loop completes 10 x 10 (100) iterations Object-Oriented Program Development Using C++
do-while loops • do-while loops • Iterates while condition true • Ends when posttest condition evaluates to false • Loop guaranteed to execute at least once • Syntax template: do{ statement(s); }while (expression); Object-Oriented Program Development Using C++
Figure 6-10 The do-while Loop Structure Object-Oriented Program Development Using C++
Figure 6-11 The do-while Statement's Flow of Control Object-Oriented Program Development Using C++
Validity Checks • do-while structure well suited to error handling • Code fragment:do{ cout << "An invalid grade was just entered\n"; cout << "Please check the grade and re-enter\n"; cin >> grade; }while (grade < MIN_GRADE || grade > MAX_GRADE); • If loop entered, guaranteed to execute at least once Object-Oriented Program Development Using C++
Program Design and Development: UML State Diagrams • State diagram: represents object states over time • Critical design step: specify events that change state • Event • Signal (or stimulus) from one object to another • Example: press button to move elevator • Basic notation • Flow line: denotes event • State: rectangle with rounded corners Object-Oriented Program Development Using C++
Figure 6-12 The State Model Identifies Operations to Be Included in the Class Diagram Object-Oriented Program Development Using C++
Figure 6-13 State Diagram Notation Object-Oriented Program Development Using C++
Program Design and Development: UML State Diagrams (continued) • Objects communicate via messages • Event attributes • Data values in message • Translate to method arguments • Action of event: occurs in zero time (instantaneously) • Activity of object: response takes place over time • Examples • Action: push door bell (or elevator) button • Activity: chimes sound (or elevator moves to floor) Object-Oriented Program Development Using C++
Figure 6-15 An Example of an Event Activity Object-Oriented Program Development Using C++
Figure 6-16 A State with an Activity Object-Oriented Program Development Using C++
Figure 6-18 A State Diagram for an Elevator Object-Oriented Program Development Using C++
Applications: Random Numbers and Simulations • Many models include statistical/probabilistic elements • Computers support models with random numbers • Random numbers • Set of numbers whose order cannot be predicted • Pseudorandom numbers: approximate random condition • General purpose C++ method: rand ( ) Object-Oriented Program Development Using C++
Scaling • rand ( ) may be adapted to floating-point data • rand ( ) may be modified to scale data values • Typical scaled range: 0.0 to 1.0 • Technique • Cast return expression to floating-point type • Divide result by RAND_MAX (compiler dependent) • rand ( ) may be used to return remainders • a + rand( ) % b • a and b represent end-points of interval Object-Oriented Program Development Using C++
Simulations • Simulations • Computer programs imitating scientific experiment • Produce important research results • Avoid overhead associated with experiments • Random numbers used extensively in simulations Object-Oriented Program Development Using C++
Coin Toss Simulation • Hypothesis: head as likely as tail (probability = .5) • Coin toss algorithm • Generates random number between 0 and 1 n times • If random number >= .5, increment heads (else tails) • Class diagram • Instance variables: heads and tosses • Main methods: flip ( ) and percentages ( ) • Results close to projections (difference < .5%) Object-Oriented Program Development Using C++
Figure 6-22 A Class Diagram for a CoinToss Class Object-Oriented Program Development Using C++
Elevator Simulation • State diagram • Action: pressing button • Activity: move to floor (iterative) • Class diagram • Two attributes: currentFloor and maxFloor • Four methods • request ( ) performs primary service • Evaluates floor request and moves to same • Uses selection and repetition structures • Driver enhanced with do-while encasing Object-Oriented Program Development Using C++
Figure 6-23 A State Diagram for an Elevator Object-Oriented Program Development Using C++
Figure 6-24 A Class Diagram for an Elevator Class Object-Oriented Program Development Using C++
Summary • Basic repetition structures: while, for, and do-while • Basic loop components: initialization, test, termination • Interactive I/O improved with repetition structures • Nesting: combining structures for complex computation • UML state diagram: event driven Object-Oriented Program Development Using C++
Summary (continued) • Action: associated with event • Activity: response associated with object • rand ( ) method generates random numbers • Random numbers simulate statistical/probabilistic patterns • Example simulations: coin toss and elevator movement Object-Oriented Program Development Using C++