Intro to the AS/400 - Florida State College at Jacksonville

Download Report

Transcript Intro to the AS/400 - Florida State College at Jacksonville

Intro to Programming
& Algorithm Design
Loops
NG Assg
Labs
This presentation can be viewed on line in a file named:
ch05.IntrotoProg.ppt
Copyright 2003 by Janson Industries
1
Objectives

Explain
 Advantages
 Different
 Common

of loops
types of loops
loop mistakes
Show how to implement the
various loop types in Java
2
Copyright 2014 by Janson Industries
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

Copyright 2014 by Janson Industries
mistakes
For example, to keep
executing with an unknown
number of data records, you
can't do it without a loop
3
Why Loops? Example

Here's pseudocode for a
program to double a number
Module main
Declare Integer numToDouble, result
Display “Enter number to double and press Enter”
Input numToDouble
result = numToDouble * 2
Display “2 X ”, numToDouble, “ = ”, result
End Module


Copyright 2014 by Janson Industries
To double another number we
have to rerun the program
For example...
4
To double another number, have to issue the java command again
We want program to just ask for another number...
5
Copyright 2014 by Janson Industries
Why Loops? Example

With a loop, we could have the
instructions run again
Module main
Declare Integer numToDouble, result
BeginLoop
Display “Enter number to double and press Enter”
Input numToDouble
result = numToDouble * 2
Display “2 X ”, numToDouble, “ = ”, result
EndLoop
End Module

And again, and again, and....
6
Copyright 2014 by Janson Industries
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
7
Copyright 2014 by Janson Industries
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
8
Copyright 2014 by Janson Industries
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
9
Copyright 2014 by Janson Industries
Loops

While loop – pre-test

Checks the condition first and
only executes if condition true
:
:
:
While hair = “dirty”
Lather
Rinse
Display "Is hair dirty or clean"
Input hair
End While
:
:
:
10
Copyright 2014 by Janson Industries
Loops

While
Condition
check done first
If check true, executes
statements
Input…
Is hair =
“dirty”
True
False
Copyright 2014 by Janson Industries

Lather
Display…
Rinse
False
Lather and rinse will not be
executed if condition is false
11
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 Industries
12
Simple pre-test loop example
Notice loop runs 4 times even though check is "counter < 4"
Control variable (counter) defined outside of loop and manipulated
13
inside loop
Copyright 2014 by Janson Industries
Loops

Do While – post-test

Checks condition at end and
executes if condition true
Do
: :
: :
While hair = “dirty”

Do Until – post-test

Checks condition at end and
executes if condition false
Do
: :
: :
Until hair = “clean”
Copyright 2014 by Janson Industries
14
Loops

Lather

Rinse
Is hair =
“dirty”
True
False
Copyright 2014 by Janson Industries
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
15
Loops


Lather
Rinse
Is hair =
“clean”
Do Until

False
True
Copyright 2014 by Janson Industries
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
16
Do While Loops

In java, do while loop syntax is
 Keyword
do
 Statements
 Keyword
to execute (in braces)
while
 Condition
(in parenthesis)
do {
statements to execute
statements to execute
} while(condition)
Copyright 2014 by Janson Industries
17
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:
Copyright 2014 by Janson Industries
if numberOfTimesToLoop = 0
18
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 execute
statements to execute
} while(!condition)
Copyright 2014 by Janson Industries
19
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
Copyright 2014 by Janson Industries
variable update value
20
For Loop

Pseudo code example:
Declare Integer ctr
For 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
Copyright 2014 by Janson Industries
the increment value as 1
21
For Loop

If you don’t specify a step value
the default is 1
Declare Integer ctr
For ctr = 1 to 2
Lather
Rinse
End For
Copyright 2014 by Janson Industries
22
For Loop


for ctr
=1 to 2
Lather
True

False
Copyright 2014 by Janson Industries
Executes a defined number
of times
In this case twice
Rinse
False
Also called a definite loop,
counted loop, counter
controlled loop
23
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 repeated
for (int ctr = 1; ctr < 3; ctr = ctr + 1)
{ statements to be repeated }
Copyright 2012 by Janson Industries
24
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

ctr = ctr + 1
 Defines
Copyright 2012 by Janson Industries
the condition to check
the increment as 1
25
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 Industries
26
Notice how much less code is needed
27
Copyright 2014 by Janson Industries
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
28
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
Copyright 2014 by Janson Industries
when it was 99
29
For Loop

Copyright 2014 by Janson Industries
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
30
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
31
For Loop
int ctr = 1
Is ctr
<3
True
Perform
Statements
ctr = ctr
+1
False
Copyright 2014 by Janson Industries
32
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
Copyright 2014 by Janson Industries
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
33
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, result
Input userInput
While (userInput > 0)
result = userInput * 2
Display result
Input userInput
End While
Copyright 2014 by Janson Industries
34
Back To Our Original Problem


Want to run doubling app until
user indicates to stop
In addition, we want to add nonlogical (aka physical)
requirements to design
 User
interface
 Formatting
35
Copyright 2014 by Janson Industries
Back To Our Original Problem

External Design (XD)
Enter number you would like to double and press Enter.
4
2x4=8
Enter number you would like to double and press Enter.
-1
OK, you entered a value <= 0, ending execution
36
Copyright 2014 by Janson Industries
Final flow chart and pseudocode
37
Copyright 2014 by Janson Industries
Notice design does not worry
about peculiarities of the
programming language
38
Copyright 2014 by Janson Industries
Create a Raptor FC and run to
verify we have the correct logic
39
Copyright 2014 by Janson Industries
import java.io.IOException;
import java.util.Scanner;
Final java class looks like this
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 results
int numToDouble = 0;
int result = 0;
//
Prints out a blank line and instruction
System.out.println(" ");
System.out.print("Enter number would you like to double and press Enter. ");
//
Priming read
numToDouble = keyboard.nextInt();
//
Start of loop and check for sentinel value
while (numToDouble > 0){
//
Calculates and displays result
result = numToDouble * 2;
System.out.println("2 X " + numToDouble + " = " + result);
40
Copyright 2014 by Janson Industries
//
Prints out a blank line and instruction
System.out.println(" ");
System.out.print("Enter number would you like to double and press
Enter. ");
//
Reads next user input
numToDouble = keyboard.nextInt();
//
End of loop
}
//
Quitting message
System.out.print("OK, you entered a value <= 0, ending execution. ");
//
End of method
}
//
}
End of class
41
Copyright 2014 by Janson Industries
With a loop, problem solved
42
Copyright 2014 by Janson Industries
Loops

Lots of reasons to use loops
Accumulating
A
shopping cart of items
 Totals
Data
validation
Declare Integer empAge
Display "Enter employee age"
Input empAge
While (empAge > 95 OR empAge < 16)
Display "Enter a valid age between 16 & 95"
Input empAge
End While
43
Copyright 2014 by Janson Industries
Totaling in a Loop
Module main
Declare Real cost, totalCost
Display “Enter first item cost"
Input cost
While (cost > 0)
totalCost = totalCost +cost
Display “Enter next item cost or zero
to end"
Input cost
End While
Display “The total cost for all items is $“ +
totalCost
End Module
44
Copyright 2014 by Janson Industries
Module main
Declare Real cost, totalCost
Declare Integer counter = 0
Display “Enter first item cost"
Can keep count of how
many items are
Input cost
entered and display
While (cost > 0)
counter = counter + 1
totalCost = totalCost +cost
Display “Enter next item cost or zero
to end"
Input cost
End While
Display “The total cost for the “ + counter
+ “ item(s) is $“ + totalCost
End Module
45
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
footer
46
Exercise XD

Report will
look like
Report Header
Page Header on Page #
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
Page Footer on Page #
47
Copyright 2014 by Janson Industries
Page Header on Page #
Exercise XD

Can be a
variable
number of
pages
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
##################################################
Page Footer on Page #
Report Footer
48
Copyright 2014 by Janson Industries
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
49
Copyright 2014 by Janson Industries
Nested
Loops
Outer
Loop
Copyright 2014 by Janson Industries
Module main
Declare Integer pageCtr = 1, lineCtr = 0
Print Report Header and Skip to next page
pageCtr = pageCtr + 1
Read record From file
While (not eof)
Print Page Header and pageCtr
While (lineCtr < 33 AND not eof)
Print item From record
Inner
lineCtr = lineCtr + 1
Loop
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
50
End Module
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
Copyright 2014 by Janson Industries
finance or interest charge
 Customer makes no new purchases
 Customer pays off the balance with
equal monthly payments of 10 percent
51
of the original balance due
Algorithm
1. Read first record from the file
2. While not eof
a. Display account number, customer name
b. Then 10 times
i. Subtract 10% from balance due
ii. Display balance due
c. Read next record from the file
52
Copyright 2014 by Janson Industries
Exercise XD

Output will look like…
Account Number: #######
Customer: Xxxxx Xxxxxx
Balance over next 10 months
########
########
########
########
########
########
########
########
########
Copyright 2014 by Janson Industries
Account Number: ########
Customer: Xxxxx Xxxxxx
Balance over next 10 months
########
53
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
54
Copyright 2014 by Janson Industries
Exercise

So in flow chart, what's first?
 Variable

definition
Then what?
 Priming
read
55
Copyright 2014 by Janson Industries
Exercise

Then what?
 While
that checks not eof
56
Copyright 2014 by Janson Industries
Exercise

Then what?
 Print
headers
57
Copyright 2014 by Janson Industries
Exercise

Then what?
 Calc
paymentAmt
58
Copyright 2014 by Janson Industries
Exercise

Then what?
 For
loop that runs 10 times to print
balances
 For
loop is nested within the while loop
59
Copyright 2014 by Janson Industries
Exercise

Then what?
 Calc
balanceDue and print it out
60
Copyright 2014 by Janson Industries
Exercise

What happens when last
balance printed?
 Blank
line
 Read
next record
 Check
for end of file
61
Copyright 2014 by Janson Industries
62
Copyright 2014 by Janson Industries
Loop Gotchas
Having an incorrect comparison
63
Copyright 2014 by Janson Industries
Loop Gotchas
Not initializing the control variable – in java, should always initialize
64
Copyright 2014 by Janson Industries
Loop Gotchas
Not changing the control variable
65
Copyright 2014 by Janson Industries
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)
66
Copyright 2014 by Janson Industries
Loop Exercise Assg 1


Program will calculate the
number of bills needed for a
dollar amount (until 0 entered)
For instance,
 Program
 What
 User
prompts user
is the dollar amount?
enters
 58
 Program
2
Copyright 2014 by Janson Industries
displays
twenty(ies), 1 ten(s), 1 five(s) and 3
67
one(s)
Loop Exercise

Attack this in two parts
How
to calculate the bills
Everything else

Design everything else first
Answer 1
68
Copyright 2014 by Janson Industries
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
 if
of ways to do calc
value > than largest denomination
• Add one to that bill counter
• Subtract denomination from amount and
check again
 else
if value > second largest
69
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
if ….
Answer 2
70
Bills Exercise Continued

Alternatively
 Divide
the amount by the biggest
denomination
 twentiesCtr
= dolls/20
• This assumes dolls is an integer so that the
decimal remainder will be truncated
 Calc
the remainder
 dollars
= dollars – (twentiesCtr * 20)
the amount by the 2nd biggest
denomination
 Divide
 etc.
Copyright 2014 by Janson Industries
Alt Answer 71
Bills Exercise Continued

Let’s prove that it works by
creating a Raptor FC
Answer 3
72
Copyright 2014 by Janson Industries
Non-graded Assg 1

Using nested loops, write a
program to display the outer loops
counter value as follows
1
22
333
4444
55555
 Don’t
use math to generate numbers
like 4,444 or 55,555

Send file, email topic Ch05Assg1
Need a hint?
Copyright 2014 by Janson Industries
73
Points to Remember

Loops are control structures
that repeat actions
 Makes
computer programs more
efficient

Four general types
 While
 DoWhile
 DoUntil
 For

Copyright 2014 by Janson Industries
Loops characterized as pretest
74
or posttest
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
75
Copyright 2014 by Janson Industries
Assignments

Non-Graded
Ch05Assg1
Chap

5 labs 4.1-4.4
Graded
Chap
5 lab 4.5
76
Copyright 2014 by Janson Industries