/
Programming Logic and Design Programming Logic and Design

Programming Logic and Design - PowerPoint Presentation

lindy-dunigan
lindy-dunigan . @lindy-dunigan
Follow
505 views
Uploaded On 2016-05-25

Programming Logic and Design - PPT Presentation

Eighth Edition Chapter 5 Looping Objectives In this chapter you will learn about The advantages of looping Using a loop control variable Nested loops Avoiding common loop mistakes Using a ID: 334330

logic loop design programming loop logic programming design edition eighth continued common figure variable control loops data applications program

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Programming Logic and Design" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Slide1

Programming Logic and DesignEighth Edition

Chapter 5

LoopingSlide2

ObjectivesIn this chapter, you will learn about:

The advantages of looping

Using a loop control variable

Nested loopsAvoiding common loop mistakesUsing a for loopCommon loop applicationsThe similarities and differences between selections and loops

2

Programming Logic and Design, Eighth EditionSlide3

Understanding the Advantages of LoopingLooping makes computer programming efficient and worthwhile

Write one set of instructions to operate on multiple, separate sets of

data

Less time required for design and codingFewer errorsShorter compile timeLoop: a structure that repeats actions while some condition continues3Programming Logic and Design, Eighth EditionSlide4

Understanding the Advantages of Looping (continued)

Dual-alternative (or binary) selection structure

Provides an action for each of two possible outcomes

4Programming Logic and Design, Eighth EditionFigure

5-1

The

loop structureSlide5

Understanding the Advantages of Looping (continued)

5

Programming Logic and Design, Eighth Edition

Figure 5-2 The

mainline logic common to many business programsSlide6

Understanding the Advantages of Looping (continued)

6

Programming Logic and Design, Eighth Edition

Quick Reference 5-1 While Statement Pseudocode StandardsSlide7

Using a Loop Control Variable

7

Programming Logic and Design, Eighth Edition

As long as a condition remains true, the statements in a while loop’s body executeControl number of repetitions Loop control variable initialized before entering loopLoop control variable testedBody of loop must alter value of loop control variable

Repetitions controlled by:Counter – used to create a definite counter-controlled loop

Sentinel value – used to create an indefinite loopSlide8

8

Programming Logic and Design, Eighth Edition

Using a Definite Loop

with a Counter

Definite loop

Executes a predetermined number of times

Counter-controlled loop

Program counts loop repetitions

Loop control variables altered by:

Incrementing

Decrementing

Counter

Any numeric variable that counts the number of times an event has occurred, usually starts with 0Slide9

Using a Definite Loop with a Counter(continued

)

9

Programming Logic and Design, Eighth EditionFigure 5-3 A counted

while loop that outputs Hello

four timesSlide10

Using an Indefinite Loop with a Sentinel Value

10

Programming Logic and Design, Eighth Edition

Indefinite loopPerformed a different number of times each time the program executesThe user decides how many times the loop executes

Figure 5-4

An indefinite

while

loop that displays

Hello

as long as the user wants to continueSlide11

Using an Indefinite Loop with a Sentinel Value (continued)

11

Programming Logic and Design, Eighth Edition

Figure

5-5

Typical executions of the program in Figure 5-4 in two

environments Slide12

Understanding the Loop in a Program’s Mainline Logic

12

Programming Logic and Design, Eighth Edition

Three steps should occur in every properly functioning loopProvide a starting value for the variable that will control the loopTest the loop control variable to determine whether the loop body executesAlter the loop control variableSlide13

Understanding the Loop in a Program’s Mainline Logic (continued)

13

Programming Logic and Design, Eighth Edition

Figure 5-6 A payroll program showing hoe the loop control variable is usedSlide14

Nested Loops

14

Programming Logic and Design, Eighth Edition

Nested loops: loops within loopsOuter loop: the loop that contains the other loopInner loop: the loop that is containedNeeded when values of two (or more) variables repeat to produce every combination of valuesSlide15

Nested Loops (continued)

15

Programming Logic and Design, Eighth Edition

Figure 5-8

Flowchart and pseudocode for

AnswerSheet

program (Continues)Slide16

Nested Loops (continued)

16

Programming Logic and Design, Eighth Edition

Figure 5-8 Flowchart and pseudocode for AnswerSheet

program (Continues)Slide17

Nested Loops (continued)

17

Programming Logic and Design, Eighth Edition

Figure 5-8 Flowchart and pseudocode for AnswerSheet

program Slide18

Nested Loops (continued)

Nested Loop facts:

Nested

loops never overlap. An inner loop is always completely contained within an outer loopAn inner loop goes through all of its iterations each time its outer loop goes through just one iterationThe total number of iterations executed by a nested loop is the number of inner loop iterations times the number of outer loop iterations18

Programming Logic and Design, Eighth EditionSlide19

Avoiding Common Loop Mistakes

19

Programming Logic and Design, Eighth Edition

Mistake: neglecting to initialize the loop control variableExample: get name statement removedValue of

name unknown or garbageProgram may end

before any labels

printed

100 labels printed

with an invalid name

Figure

5-9

Correct

logic for greeting

programSlide20

Avoiding Common Loop Mistakes (continued)

20

Programming Logic and Design, Eighth Edition

Figure 5-10 Incorrect logic for greeting program because the loop control variable initialization is missingSlide21

Avoiding Common Loop Mistakes (continued)

21

Programming Logic and Design, Eighth Edition

Mistake: neglecting to alter the loop control variableRemove get name instruction from

outer loopUser never enters a

name

after the first

one

Inner loop executes

infinitely

Always incorrect to

create

a loop that

cannot

terminate

Figure

5-11

Incorrect

logic for greeting

program because the loop control variable is not alteredSlide22

Avoiding Common Loop Mistakes (continued)

22

Programming Logic and Design, Eighth Edition

Mistake: using the wrong comparison with the loop control variableProgrammers must use correct comparisonSeriousness depends on actions performed within a loopOvercharge insurance customer by one monthOverbook a flight on airline application

Dispense extra medication to patients in pharmacySlide23

Avoiding Common Loop Mistakes (continued)

23

Programming Logic and Design, Eighth Edition

Figure 5-12 Incorrect logic for greeting

program because the loop control variable is not alteredSlide24

Avoiding Common Loop Mistakes (continued)

24

Programming Logic and Design, Eighth Edition

Mistake: including statements inside the loop that belong outside the loopExample: discount every item by 30 percentInefficient because the same value is calculated 100 separate times for each price that is enteredMove outside the loop for efficiencySlide25

Avoiding Common Loop Mistakes (continued)

25

Programming Logic and Design, Eighth Edition

Figure 5-13 Inefficient way to produce 100 discount price stickers for differently priced items (Continues)Slide26

Avoiding Common Loop

Mistakes

(continued)

26Programming Logic and Design, Eighth Edition

Figure 5-13

Inefficient way to produce 100 discount price stickers for differently priced

items (Continues)Slide27

Avoiding Common Loop Mistakes (continued)

27

Programming Logic and Design, Eighth Edition

Figure 5-14 Improved discount sticker-making program

(Continues)Slide28

Avoiding

Common Loop Mistakes

(continued)

28Programming Logic and Design, Eighth Edition

Figure 5-14

Improved discount sticker-making

programSlide29

Using a for Loop

29

Programming Logic and Design, Eighth Edition

for statement or for loop is a definite loopProvides three actions in one structure

InitializesEvaluatesAlters

Figure 5-15

Comparable

while

and

for

statements that each output

Hello

four timesSlide30

Using a for Loop (continued)

30

Programming Logic and Design, Eighth Edition

Examplefor count = 0 to 3 step 1 output "Hello"

endforInitializes count variable to 0

Checks

count

variable against the limit value 3

If evaluation is true,

for

statement body prints the word “Hello”

Increases

count

by 1 using a

step valueSlide31

Using a for Loop (continued)

31

Programming Logic and Design, Eighth Edition

Step value: the amount by which a loop control variable changesCan be positive or negative (incrementing or decrementing the loop control variable)Default step value is 1Programmer specifies a step value when each pass through the loop changes the loop control variable by a value other than 1Slide32

32

Programming Logic and Design, Eighth Edition

Using a

for

Loop

(continued)

Quick Reference 5-2

for Statement Pseudocode StandardsSlide33

Using a for Loop (continued)

33

Programming Logic and Design, Eighth Edition

while statement could be used in place of for statementPretest loop: the loop control variable is tested before each iterationfor

loops and while loops are pretest loops

Posttest loop

: the loop control variable is tested after each iteration

do…while

is a posttest loopSlide34

Common Loop Applications

34

Programming Logic and Design, Eighth Edition

Using a loop to accumulate totalsExamplesBusiness reports often include totalsList of real estate sold and total valueAccumulator: variable that gathers valuesSimilar to a counterCounter increments by 1

Accumulator increments by some valueSlide35

Common Loop Applications (continued)

35

Programming Logic and Design, Eighth Edition

Accumulators require three actionsInitialize the accumulator to 0Accumulators are altered: once for every data set processedAt the end of processing, accumulators are outputSummary reportsContain only totals with no detail data

Loops are processed but detail information is not printedSlide36

Common Loop Applications (continued)

36

Programming Logic and Design, Eighth Edition

Figure 5-16 Month-end real estate sales reportSlide37

Common Loop Applications (continued)

37

Programming Logic and Design, Eighth Edition

Figure 5-17 Flowchart and pseudocode for real estate sales report program (Continues)Slide38

Common Loop Applications (continued)

38

Programming Logic and Design, Eighth Edition

Figure 5-17 Flowchart and pseudocode for real estate sales report program (Continues)Slide39

Common Loop Applications (continued)

39

Programming Logic and Design, Eighth Edition

Using a loop to validate dataDefensive programming: preparing for all possible errors before they occurWhen prompting a user for data, no guarantee that data is validValidate data: make sure data falls in acceptable ranges (month values between 1 and 12)GIGO: Garbage in, garbage out

Unvalidated input will result in erroneous outputSlide40

Common Loop Applications (continued)

40

Programming Logic and Design, Eighth Edition

Figure 5-18 Reprompting a user once after an invalid month is enteredSlide41

Common Loop Applications (continued)

41

Programming Logic and Design, Eighth Edition

Figure 5-19 Reprompting a user continuously after an invalid month is enteredSlide42

Common Loop Applications (continued)

42

Programming Logic and Design, Eighth Edition

Limiting a reprompting loopReprompting can be frustrating to a user if it continues indefinitelyMaintain a count of the number of repromptsForcing a data item means: Override incorrect data by setting the variable to a specific valueSlide43

Common Loop Applications (continued)

43

Programming Logic and Design, Eighth Edition

Figure 5-20 Limiting user repromptsSlide44

Common Loop Applications (continued)

44

Programming Logic and Design, Eighth Edition

Validating a data typeValidating data requires a variety of methodsisNumeric() or similar methodProvided with the language translator you use to write your programsBlack box

isChar()

or

isWhitespace()

Accept user data as strings

Use built-in methods to convert to correct data typesSlide45

45

Programming Logic and Design, Eighth Edition

Figure

5-21 Checking data for correct type

Common Loop Applications

(continued)Slide46

Common Loop Applications (continued)

46

Programming Logic and Design, Eighth Edition

Validating reasonableness and consistency of dataMany data items can be checked for reasonablenessGood defensive programs try to foresee all possible inconsistencies and errorsSlide47

Common Loop Applications

(continued)

Comparing Selections

and LoopsSelection StructureThe two logical paths (True and False) join togetherLoop StructureOne of the logical

branches returns to the same decision

47

Programming Logic and Design, Eighth Edition

Figure

5-22

Comparing a selection and a loopSlide48

Common Loop Applications (continued)

48

Programming Logic and Design, Eighth Edition

Figure 5-23 Inefficient logic for reading and displaying employee recordsSlide49

Common Loop Applications (continued)

49

Programming Logic and Design, Eighth Edition

Figure 5-24 Efficient and structured logic for getting and displaying employee recordsSlide50

Summary

50

Programming Logic and Design, Eighth Edition

Loops write one set of instructions that operate on multiple, separate sets of dataThree steps must occur in every loopInitialize the loop control variableCompare the variable to some valueAlter the variable that controls the loopNested loops: loops within loopsNested loops maintain two individual loop control variables

Alter each at the appropriate timeSlide51

Summary (continued)

51

Programming Logic and Design, Eighth Edition

Common mistakes made by programmersNeglecting to initialize the loop control variableNeglecting to alter the loop control variableUsing the wrong comparison with the loop control variableIncluding statements inside the loop that belong outside the loopMost computer languages support a for

statementfor loop used when the number of iterations is known

Loops are used to accumulate totals in business reports and to reprompt users for valid dataSlide52

Summary (continued)

52

Programming Logic and Design, Eighth Edition

In the Selection Structure the two logical paths that emerge from the decision join together following their actionsIn the loop structure, the paths that emerge from the decision do not join togetherInstead, with a loop, one of the logical branches that emerges from the structure-controlling decision eventually returns to the same

decision