16. Controlling Loops CSC-3004 Introduction to Software Development

Slides:



Advertisements
Similar presentations
Repeating Actions While and For Loops
Advertisements

Introduction to Computers and Programming Lecture 9: For Loops New York University.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Loops and Files.
Objectives You should be able to describe:
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.
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.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Flow Control. Comments u Comments: /* This is a comment */ –Use them! –Comments should explain: v special cases v the use of functions (parameters, return.
Topic 4: Looping Statements
Chapter 6: Loops.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Control Structures II (Repetition)
16. Controlling Loops CSC-3004 Introduction to Software Development
Introduction To Repetition The for loop
The switch Statement, and Introduction to Looping
Lecture 7: Repeating a Known Number of Times
Programming Logic and Design Fourth Edition, Comprehensive
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Loop Structures.
Control Structures II (Repetition)
Chapter 5: Repetition Structures
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
JavaScript: Control Statements.
Chapter 8: Control Structures
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Designing and Debugging Batch and Interactive COBOL Programs
Looping and Repetition
Switch Statements, Do While, Break, Continue, Goto, Comma Operator
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Structured Programming Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Chapter 6: Repetition Statements
CSC115 Introduction to Computer Programming
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe: The while Statement
More Loops Topics Counter-Controlled (Definite) Repetition
Repetition Statements (Loops) - 2
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
More Loops Topics Counter-Controlled (Definite) Repetition
Loops.
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
REPETITION Why Repetition?
Looping and Repetition
Presentation transcript:

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

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

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.

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

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

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

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!

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

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

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

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.

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

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 );

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.

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

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

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.

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.

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.

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)

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.

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

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 );

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.

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(); }

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.

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

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.