2Object-Oriented Program Development Using C++ 3 Basic Loop Structures Loops repeat execution of an...
-
Upload
tiffany-jackson -
Category
Documents
-
view
214 -
download
1
Transcript of 2Object-Oriented Program Development Using C++ 3 Basic Loop Structures Loops repeat execution of an...
2Object-Oriented Program Development Using C++
3Object-Oriented Program Development Using C++
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
4Object-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
5Object-Oriented Program Development Using C++
Figure 6-1A Pretest Loop
6Object-Oriented Program Development Using C++
Figure 6-2A Posttest Loop
7Object-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
8Object-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
9Object-Oriented Program Development Using C++
Figure 6-3Structure of a while Loop
10Object-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
11Object-Oriented Program Development Using C++
Figure 6-4Flow of Control for Program 6-5
12Object-Oriented Program Development Using C++
Figure 6-5Accepting and Adding a Number to a Total
13Object-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
14Object-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
15Object-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
16Object-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
17Object-Oriented Program Development Using C++
Figure 6-7for Loop Control
18Object-Oriented Program Development Using C++
Figure 6-8Simplified for Loop Flowchart
19Object-Oriented Program Development Using C++
Nested Loops
• Nested loops: loops within other control structures– Add dimensionality to data
• Code fragmentfor (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
20Object-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);
21Object-Oriented Program Development Using C++
Figure 6-10The do-while Loop Structure
22Object-Oriented Program Development Using C++
Figure 6-11The do-while Statement's Flow of Control
23Object-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
24Object-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
25Object-Oriented Program Development Using C++
Figure 6-12The State Model Identifies Operations to Be Included in the Class Diagram
26Object-Oriented Program Development Using C++
Figure 6-13State Diagram Notation
27Object-Oriented Program Development Using C++
• 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)
Program Design and Development: UML State Diagrams (continued)
28Object-Oriented Program Development Using C++
Figure 6-15An Example of an Event Activity
29Object-Oriented Program Development Using C++
Figure 6-16A State with an Activity
30Object-Oriented Program Development Using C++
Figure 6-18A State Diagram for an Elevator
31Object-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 ( )
32Object-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
33Object-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
34Object-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%)
35Object-Oriented Program Development Using C++
Figure 6-22A Class Diagram for a CoinToss Class
36Object-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
37Object-Oriented Program Development Using C++
Figure 6-23A State Diagram for an Elevator
38Object-Oriented Program Development Using C++
Figure 6-24A Class Diagram for an Elevator Class
39Object-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
40Object-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