Presentation is loading. Please wait.

Presentation is loading. Please wait.

16. Controlling Loops CSC-3004 Introduction to Software Development

Similar presentations


Presentation on theme: "16. Controlling Loops CSC-3004 Introduction to Software Development"— Presentation transcript:

1 16. Controlling Loops CSC-3004 Introduction to Software Development
Spring 2015 Dr. James Skon

2 Loops "Loop" is an informal term that refers to any kind of iterative control structure—any structure that causes a program to repeatedly execute a block of code. Common loop types are for, while, and do- while in C++ and Java

3 Loop Types The counted loop - performed a specific number of times.
Continuously evaluated loop - how many times unknown at beginning, determined by external conditions. Endless loop - executes forever once it has started. Iterator loop - performs its action once for each element in a container class.

4 Loop Kind Compare – C, C++, C#, Java
Kind of Loop Flexibility Test Location for flexible beginning while do-while end foreach* Rigid * C#

5 When to use WHILE loop Test for exit is performed once per loop:
WHILE – Test at beginning DO-WHILE – Test at End How do you choose? WHILE may execute zero times DO-WHILE will ALWAYS execute once

6 LOOP-WITH-EXIT LOOP A loop-with-exit loop usually consists of the loop beginning, the loop body (including an exit condition), and the loop end. This idea is that you can bail out of the loop if some condition becomes true in the middle of the code body

7 LOOP example without EXIT
What’s the problem? // Compute scores and ratings. score = 0; GetNextRating( &ratingIncrement ); rating = rating + ratingIncrement; while ( ( score < targetScore ) && ( ratingIncrement != 0 ) ) { GetNextScore( &scoreIncrement ); score = score + scoreIncrement; } WHY?? Repeated Code! Repeated Code leads to maintenance issues!

8 Loop-With-Exit Loop loop-exit condition
// Compute scores and ratings. The code uses an infinite loop // and a break statement to emulate a loop-with-exit loop. score = 0; while ( true ) { GetNextRating( &ratingIncrement ); rating = rating + ratingIncrement; if ( !((score < targetScore) && (ratingIncrement != 0))) { break; } GetNextScore( &scoreIncrement ); score = score + scoreIncrement; loop-exit condition

9 Loop-and-a-half Don’t do on first pass
goto Start; while ( expression ) { // do something ... Start: // do something else }

10 Abnormal Loop-With-Exit Loops
while ( true ) { // do something else ... if ( !( expression ) ) { break; } // do something

11 FOR loop A for loop is a good choice when you need a loop that executes a specified number of times. Don't explicitly change the index value of a for loop to force it to terminate. Use a while loop instead.

12 C# FOREACH LOOP Useful for performing an operation on each member of an array or other container. It has the advantage of eliminating loop- housekeeping arithmetic

13 C# FOREACH LOOP int [] fibonacciSequence = new int [] { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 }; int oddFibonacciNumbers = 0; int evenFibonacciNumbers = 0; // count the number of odd and even numbers in a Fibonacci sequence foreach ( int fibonacciNumber in fibonacciSequence ) { if ( fibonacciNumber % 2 ) == 0 ) { evenFibonacciNumbers++; } else { oddFibonacciNumbers++; Console.WriteLine( "Found {0} odd numbers and {1} even numbers.", oddFibonacciNumbers, evenFibonacciNumbers );

14 Controlling the Loop – common problems
incorrect or omitted loop initialization omitted initialization of accumulators or other variables related to the loop improper nesting incorrect termination of the loop forgetting to increment a loop variable or incrementing the variable incorrectly indexing an array element from a loop index incorrectly.

15 Two practices to minimize errors
minimize the number of factors that affect the loop – SIMPLIFY! treat the inside of the loop as if it were a routine. Keep the control OUTSIDE of the loop Explicitly state conditions under which the body is executed Reader shouldn’t need to look INTO the lop body to understand the loop control

16 Treat loop body like black box
while ( !inputFile.EndOfFile() && moreDataAvailable ) { }

17 ENTERING THE LOOP Enter the loop from one location only.
A variety of loop-control structures allows you to test at the beginning, middle, or end of a loop. These structures are rich enough to allow you to enter the loop from the top every time. You don't need to enter a loop at multiple locations.

18 ENTERING THE LOOP Put initialization code directly before the loop.
The Principle of Proximity advocates putting related statements together. If related statements are strewn across a routine, it's easy to overlook them during modification and to make the modifications incorrectly. If related statements are kept together, it's easier to avoid errors during modification.

19 ENTERING THE LOOP Keep loop-initialization statements with the loop they're related to. If you don't, you're more likely to cause errors when you generalize the loop into a bigger loop and forget to modify the initialization code.

20 INFINITE LOOPS Use while( true ) for infinite loops. Some use for {;;}
Use these for loops that will never exit (main menu checking loop, control loop for pace- maker.) Also use for loop with “event” termination, exits on external event (on.mouseclick or on.error, for example)

21 WHILE or FOR Don't use a for loop when a while loop is more appropriate A common abuse of the flexible for loop structure is haphazardly cramming the contents of a while loop into a for loop header.

22 WHILE or FOR // read all the records from a file for ( inputFile.MoveToStart(), recordCount = 0; !inputFile.EndOfFile(); recordCount++ ) { inputFile.GetRecord(); }

23 The Loop Body Use { and } to enclose the statements in a loop – ALWAYS
Avoid empty loops In C++ and Java while ( ( inputChar = dataFile.GetChar() ) != CharType_Eof ) { ; } do { inputChar = dataFile.GetChar(); } while ( inputChar != CharType_Eof );

24 Housekeeping Statements
Keep loop-housekeeping chores at either the beginning or the end of the loop. expressions like i = i + 1 or j++ that control the loop As a general rule, the variables you initialize before the loop are the variables you'll manipulate in the housekeeping part of the loop.

25 Housekeeping Statements
nameCount = 0; totalLength = 0; while ( !inputFile.EndOfFile() ) { // do the work of the loop inputFile >> inputString; names[ nameCount ] = inputString; ... // prepare for next pass through the loop— // housekeeping nameCount++; totalLength = totalLength + inputString.length(); }

26 EXITING THE LOOP Assure yourself that the loop ends.
Make loop-termination conditions obvious. Don't monkey with the loop index of a for loop to make the loop terminate.

27 EXITING THE LOOP for ( int i = 0; i < 100; i++ ) { // some code ... if ( ... ) { i = 100; } // more code Oh my!!!

28 EXITING THE LOOP Avoid code that depends on the loop index's final value. It's bad form to use the value of the loop index after the loop. The terminal value of the loop index varies from language to language and implementation to implementation.

29

30


Download ppt "16. Controlling Loops CSC-3004 Introduction to Software Development"

Similar presentations


Ads by Google