1 intro to programming & algorithm design loops copyright 2003 by janson industries this...

76
1 Programming & Algorithm Design Loops right 2003 by Janson Industries This presentation can be viewed on line in a file named: ch05.IntrotoProg.ppt Labs NG Assg

Upload: sharlene-simon

Post on 02-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

1

Intro to Programming & Algorithm Design

Loops

Copyright 2003 by Janson Industries

This presentation can be viewed on line in a file named: ch05.IntrotoProg.ppt

LabsNG Assg

Copyright 2014 by Janson Industries2

Objectives Explain

Advantages of loops

Different types of loops

Common loop mistakes

Show how to implement the various loop types in Java

Copyright 2014 by Janson Industries3

Why Loops? If a set of instructions needs to be

repeated many times, best to use a loop rather than repeating the instructions Less coding

Fewer mistakes

For example, to keep executing with an unknown number of data records, you can't do it without a loop

Copyright 2014 by Janson Industries4

Why Loops? Example Here's pseudocode for a program to double a number

To double another number we have to rerun the program

For example...

Module mainDeclare Integer numToDouble, result

Display “Enter number to double and press Enter”Input numToDoubleresult = numToDouble * 2 Display “2 X ”, numToDouble, “ = ”, result

End Module

Copyright 2014 by Janson Industries5

To double another number, have to issue the java command again

We want program to just ask for another number...

Copyright 2014 by Janson Industries6

Why Loops? Example With a loop, we could have the instructions run again

And again, and again, and....

Module mainDeclare Integer numToDouble, resultBeginLoop

Display “Enter number to double and press Enter”

Input numToDoubleresult = numToDouble * 2 Display “2 X ”, numToDouble, “ = ”, result

EndLoopEnd Module

Copyright 2014 by Janson Industries7

Why Loops? This is why loops have to check a control variable to see if they should process the statements again

How and when the check is done is the difference between the different types of loops Condition-controlled

Count-controlled

Copyright 2014 by Janson Industries8

Why Loops? Condition-controlled loops use a true/false condition to determine how many times to loop

While executes when condition true

Do While executes when condition true

Do Until executes when condition false

Count-controlled loops execute a specific number of times For

Copyright 2014 by Janson Industries9

Why Loops? Condition-controlled loops also

differentiated by when the condition is checked While is a pre-test loop

Do While is a post-test loop

Do Until is a post-test loop

Copyright 2014 by Janson Industries10

While loop – pre-test

Checks the condition first and only executes if condition true

Loops

: : :While hair = “dirty”

Lather Rinse Display "Is hair dirty or clean" Input hairEnd While : : :

Copyright 2014 by Janson Industries 11

Loops While

Condition check done first If check true, executes

statements

Lather and rinse will not be executed if condition is false

Is hair = “dirty”

FalseLather RinseTrue

False

Input… Display…

Copyright 2014 by Janson Industries 12

Loops In While, Do While, and Do Until loops, the

programmer explicitly manipulates the control variable(s)

In java, while loop syntax is Keyword while

Condition (in parenthesis)

Statements to execute (in braces) while (condition) { statements to execute }

Copyright 2014 by Janson Industries13

Simple pre-test loop exampleNotice loop runs 4 times even though check is "counter < 4"

Control variable (counter) defined outside of loop and manipulated inside loop

Copyright 2014 by Janson Industries14

Do While – post-test Checks condition at end and

executes if condition true

Do Until – post-test Checks condition at end and

executes if condition false

Loops

Do : : : :

While hair = “dirty”

Do : : : :

Until hair = “clean”

Copyright 2014 by Janson Industries 15

Loops Do While condition test done at end of loop

Lather and rinse will always be executed at least once whether the condition is true or not but only continues if true

Is hair = “dirty”

Lather

Rinse

True

False

Copyright 2014 by Janson Industries 16

Loops Do Until

Condition test done at end of loop

Lather and rinse will always be executed at least once whether the condition is true or not but only continues if false

Is hair = “clean”

Lather

Rinse

False

True

Copyright 2014 by Janson Industries 17

Do While Loops In java, do while loop syntax is

Keyword do Statements to execute (in braces) Keyword while Condition (in parenthesis)

do { statements to executestatements to execute

} while(condition)

Copyright 2014 by Janson Industries18

Simple post-test loop example - Notice loop runs 4 times (just like pretest)

What condition(s) would result in different output for the different loop types?

Answer: if numberOfTimesToLoop = 0

Copyright 2014 by Janson Industries 19

Do Until Loops In java, there is no Do Until

Closest you can come to a Do Until is use a Do While and negate the condition

do { statements to executestatements to execute

} while(!condition)

Copyright 2014 by Janson Industries 20

For Loop A little complicated

Does a lot of stuff very compactly

Most for statements allow the programmer to specify A loop control variable

An initial value for the variable

An evaluation condition A Boolean expression with the loop control variable

A variable update value

Copyright 2014 by Janson Industries 21

For Loop Pseudo code example:Declare Integer ctrFor ctr = 1 to 3 step 1

statements to be repeated

End For

Declare Integer ctr Defines the loop control variable ctr

ctr = 1 to 3 Initializes ctr to 1 and defines the max value for ctr

step 1 defines the increment value as 1

Copyright 2014 by Janson Industries 22

For Loop If you don’t specify a step value

the default is 1

Declare Integer ctrFor ctr = 1 to 2

Lather Rinse

End For

Copyright 2014 by Janson Industries 23

For Loop Executes a defined number

of times In this case twice

Also called a definite loop, counted loop, counter controlled loop

for ctr=1 to 2

FalseLather RinseTrue

False

Copyright 2012 by Janson Industries 24

Java For Loop The for keyword Then in parenthesis

Loop control variable definition (optional) and initialization Semicolon The loop condition evaluation Semicolon The step increment definition

Then in braces the statements to be repeatedfor (int ctr = 1; ctr < 3; ctr = ctr + 1) { statements to be repeated }

Copyright 2012 by Janson Industries 25

Java For Loop Example

for (int ctr = 1; ctr < 3; ctr = ctr + 1) {statements to be repeated }

int ctr = 1 Creates the variable ctr Initializes ctr to 1

ctr < 3 Defines the condition to check

ctr = ctr + 1 Defines the increment as 1

Copyright 2014 by Janson Industries 26

For Loop If the loop is going to execute a fixed

number of times For loop easier than while or do while

Instead of statements to Define the control variable Define the limit Increment the control variable And the do or do while keywords

You use the for statement to do all those things

Copyright 2014 by Janson Industries27

Notice how much less code is needed

Copyright 2014 by Janson Industries 28

For Loop To truly understand the For loop,

you have to understand

The generally accepted interpretation of the pseudocode and/or flowchart text

When all the "pieces" of the for statement are performed

Copyright 2014 by Janson Industries 29

For Loop If the pseudocode had specified

0 to 99 (0 and 99 are inclusive)

It means the statements should be executed 100 times

Once when it was 0

Once when it was 1

Etc, etc, etc

Once when it was 99

Copyright 2014 by Janson Industries 30

For Loop To get the for loop to work the

same way with java, could specify any of these int ctr = 0; ctr <100; ctr = ctr + 1

int ctr = 0; ctr <= 99; ctr = ctr + 1

int ctr = 1; ctr <101; ctr = ctr + 1

int ctr = 1; ctr <= 100; ctr = ctr + 1

Copyright 2014 by Janson Industries 31

For Loop Why? Because the for does

"int ctr = 1" first and only once

Then repeatedly The condition is checked If condition is true

• Statements are executed• Ctr is incremented by one

When the condition is false The statement after the End For is

executed

Copyright 2014 by Janson Industries 32

For Loop

Is ctr < 3

int ctr = 1

True

False

PerformStatements

ctr = ctr +1

Copyright 2014 by Janson Industries 33

For Loop In the pseudocode 1 to 2 means

Do the statements while the control variable is equal to 1 or 2

This means The variable is initially set to 1 Condition is checked The statements are performed The variable is incremented to 2 Condition is checked The statements are performed The variable is incremented to 3 Condition is checked The statement after the End For is performed

Copyright 2014 by Janson Industries34

Sentinel Values Sometimes you want a loop to execute until a user enters a value the means “stop the loop”

Called a sentinel value

While or Do While best for this

Declare Integer userInput, resultInput userInputWhile (userInput > 0) result = userInput * 2

Display resultInput userInput

End While

Copyright 2014 by Janson Industries35

Back To Our Original Problem Want to run doubling app until user indicates to stop

In addition, we want to add non-logical (aka physical) requirements to design User interface

Formatting

Copyright 2014 by Janson Industries36

Back To Our Original Problem External Design (XD)

Enter number you would like to double and press Enter. 42 x 4 = 8

Enter number you would like to double and press Enter.-1OK, you entered a value <= 0, ending execution

Copyright 2014 by Janson Industries37

Final flow chart and pseudocode

Copyright 2014 by Janson Industries38

Notice design does not worry about peculiarities of the programming language

Copyright 2014 by Janson Industries39

Create a Raptor FC and run to verify we have the correct

logic

Copyright 2014 by Janson Industries40

import java.io.IOException;import java.util.Scanner;

public class DoubleWithWhile {

public static void main(String[] args) {// Variable and object needed to read from command line

Scanner keyboard = new Scanner(System.in);

// Variables needed to hold input, intermediate values, and resultsint numToDouble = 0;int result = 0;

// Prints out a blank line and instructionSystem.out.println(" ");System.out.print("Enter number would you like to double and press Enter. ");

// Priming readnumToDouble = keyboard.nextInt();

// Start of loop and check for sentinel valuewhile (numToDouble > 0){

// Calculates and displays result result = numToDouble * 2;System.out.println("2 X " + numToDouble + " = " + result);

Final java class looks like this

Copyright 2014 by Janson Industries41

// Prints out a blank line and instructionSystem.out.println(" ");System.out.print("Enter number would you like to double and press Enter.

");

// Reads next user inputnumToDouble = keyboard.nextInt();

// End of loop}

// Quitting messageSystem.out.print("OK, you entered a value <= 0, ending execution. ");

// End of method}

// End of class}

Copyright 2014 by Janson Industries42

With a loop, problem solved

Copyright 2014 by Janson Industries43

Loops Lots of reasons to use loops

Accumulating A shopping cart of itemsTotals

Data validation

Declare Integer empAgeDisplay "Enter employee age" Input empAgeWhile (empAge > 95 OR empAge < 16)

Display "Enter a valid age between 16 & 95" Input empAge

End While

Copyright 2014 by Janson Industries44

Totaling in a LoopModule main

Declare Real cost, totalCostDisplay “Enter first item cost" Input costWhile (cost > 0)

totalCost = totalCost +cost Display “Enter next item cost or

zero to end" Input cost

End WhileDisplay “The total cost for all items is $“ ,

totalCostEnd Module

Copyright 2014 by Janson Industries45

Module mainDeclare Real cost, totalCostDeclare Integer counter = 0Display “Enter first item cost" Input costWhile (cost > 0)

counter = counter + 1totalCost = totalCost +cost Display “Enter next item cost or

zero to end" Input cost

End WhileDisplay “The total cost for the “ , counter

, “ item(s) is $“ , totalCostEnd Module

Can keep count of how many items are entered and display

Copyright 2014 by Janson Industries46

Nested Loops Loops within loops

Example, a report that reads and prints a file's contents and has the following format: Report header For each page

A page header with page number For next 33 items

• Print line item

A page footer with page number Report footer

Copyright 2014 by Janson Industries47

Exercise XD Report will

look likePage Header on Page #################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##

Page Footer on Page #

Report Header

Copyright 2014 by Janson Industries48

Exercise XD Can be a variable

number of pages

Page Header on Page #################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##################################################

##

Page Footer on Page #

Report Footer

Copyright 2014 by Janson Industries49

Nested Loops When a file is read, system

returns a boolean value to indicate if there is anymore data

Called an "end of file" indicator

Indicator abbreviated as eof

eof has a boolean value of true or false

Can be used to control looping

Copyright 2014 by Janson Industries50

Nested Loops

OuterLoop

InnerLoop

Module mainDeclare Integer pageCtr = 1, lineCtr = 0Print Report Header and Skip to next pagepageCtr = pageCtr + 1Read record From fileWhile (not eof)

Print Page Header and pageCtr While (lineCtr < 33 AND not eof) Print item From record

lineCtr = lineCtr + 1 Read record From file

End While lineCtr = 0 Print Page Footer and pageCtr Skip to next page pageCtr = pageCtr + 1

End While Print Report Footer

End Module

Copyright 2014 by Janson Industries51

Exercise Design (SFC) an application that:

Gets customer account data from a file that has account number, customer name, and balance due

For each customer: Print the account number and name Then for each month for the next 10

months • Print the customer’s projected balance

Assume: No finance or interest charge Customer makes no new purchases Customer pays off the balance with

equal monthly payments of 10 percent of the original balance due

Copyright 2014 by Janson Industries52

Algorithm

1. Read first record from the file2. While not eof

a. Display account number, customer nameb. Then 10 times

i. Subtract 10% from balance dueii. Display balance due

c. Read next record from the file

Copyright 2014 by Janson Industries53

Exercise XD Output will look like…

Account Number: #######Customer: Xxxxx XxxxxxBalance over next 10 months########################################################################

Account Number: ########Customer: Xxxxx XxxxxxBalance over next 10 months########

Copyright 2014 by Janson Industries54

Exercise What's input and what variables

will you need to hold them? acctNum for Account number custName for Customer name balanceDue for Balance due

Based on calculation what variables will you need to hold intermediary and results? paymentAmt for 10 percent of the

balance

Copyright 2014 by Janson Industries55

Exercise So in flow chart, what's first?

Variable definition Then what?

Priming read

Copyright 2014 by Janson Industries56

Exercise Then what?

While that checks not eof

Copyright 2014 by Janson Industries57

Exercise Then what? Print headers

Copyright 2014 by Janson Industries58

Exercise Then what? Calc paymentAmt

Copyright 2014 by Janson Industries59

Exercise Then what? For loop that runs 10 times to print

balances For loop is nested within the while loop

Copyright 2014 by Janson Industries60

Exercise Then what?

Calc balanceDue and print it out

Copyright 2014 by Janson Industries61

Exercise What happens when last balance

printed? Blank line

Read next record

Check for end of file

Copyright 2014 by Janson Industries62

Copyright 2014 by Janson Industries63

Having an incorrect comparison

Loop Gotchas

Copyright 2014 by Janson Industries64

Not initializing the control variable – in java, should always initialize

Loop Gotchas

Copyright 2014 by Janson Industries65

Not changing the control variable

Loop Gotchas

Copyright 2014 by Janson Industries66

Loop Gotchas The last example resulted in an

infinite loop The condition is never false Loop statements continually executed

Can also happen because of a bad/trivial condition (always true) 1 == 1

End program execution by pressing and holding Ctrl key and then pressing C key (Crtl + C)

Copyright 2014 by Janson Industries67

Loop Exercise Assg 1 Program will calculate the number of

bills needed for a dollar amount (until 0 entered)

For instance,

Program prompts user What is the dollar amount?

User enters 58

Program displays 2 twenty(ies), 1 ten(s), 1 five(s) and 3

one(s)

Copyright 2014 by Janson Industries68

Loop Exercise

Attack this in two parts How to calculate the bills Everything else

Design everything else first

Answer 1

Copyright 2014 by Janson Industries69

Bills Exercise Continued How to figure out the number of

bills a little trickier

First: you need variables to keep track of the number of bills for each denomination (bill counters)

Couple of ways to do calc if value > than largest denomination

• Add one to that bill counter• Subtract denomination from amount and

check again

else if value > second largest

Copyright 2014 by Janson Industries70

Bills Exercise Continued So for example, if 58 (dollars)

entered

Check if dollars is bigger than 20 Yes

Add one to 20 counter Subtract 20 from dollars, check again

No if value > than 2nd largest denomination

• Add one to that bill counter

• Subtract denomination from dollars and check again

else if …. Answer 2

Copyright 2014 by Janson Industries71

Bills Exercise Continued Alternatively

Divide the amount by the biggest denomination

twentiesCtr = dollars/20 • This assumes dolls is an integer so that the

decimal remainder will be truncated

Calc the remainder dollars = dollars – (twentiesCtr * 20)

Divide the amount by the 2nd biggest denomination

etc.

Alt Answer

Copyright 2014 by Janson Industries72

Bills Exercise Continued

Let’s prove that it works by creating a Raptor FC

Answer 3

Copyright 2014 by Janson Industries73

Non-graded Assg 1 Using nested loops, write a program to display the outer loops counter value as follows

Don’t use math to generate numbers like 4,444 or 55,555 Send file, email topic Ch05Assg1

Need a hint?

122333444455555

Copyright 2014 by Janson Industries74

Points to Remember Loops are control structures that

repeat actions Makes computer programs more

efficient

Four general types While DoWhile DoUntil For

Loops characterized as pretest or posttest

Copyright 2014 by Janson Industries75

Points to Remember All require

A loop control variable Which must be initialized and

updated

A condition that tests the control variable against a sentinel value

Can be nested

Beware the infinite loop

Copyright 2014 by Janson Industries

Assignments Non-Graded

Ch05Assg1

Chap 5 labs 4.1-4.4

Graded

Chap 5 lab 4.5

76