Iteration - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

Iteration

Description:

Know how to use the basic looping structures in Java (while, ... netWorth = wage; //payday. System.out.println( 'Your net worth after ' days ' days is ' ... – PowerPoint PPT presentation

Number of Views:74
Avg rating:3.0/5.0
Slides: 28
Provided by: drtimm8
Category:
Tags: iteration

less

Transcript and Presenter's Notes

Title: Iteration


1
Iteration
  • Dr. Tim Margush
  • University of Akron

2
Goals
  • Know how to use the basic looping structures in
    Java (while, for, and do)
  • Be able to implement nested structures when
    appropriate
  • Understand typical design methods for handing
    input
  • Explore random simulation techniques

3
Iteration
  • Basic Control Structures
  • Sequence
  • Decision
  • Iteration (repetition, looping)
  • Java provides 3 basic iteration structures
  • while
  • do
  • for

4
While Loop
  • Java's while structure
  • Allows a statement to be repeated 0 or more times
  • Repetition is controlled by a Boolean expression
  • Warning
  • Loops may never end

But the cat came back the very next day,The cat
came back, we thought he was a gonerBut the cat
came back it just couldn't stay away.Away,
away, yea, yea, yea
5
While Syntax
//How to become a millionaire
  • while (expression) statement
  • while (expression)
  • Statement list

netWorthlt 1e6?
netWorthdeposit
true branch (iterate)
false branch (exit)
Block Statement
6
Application Input Validation
  • The task is to require a user to enter a positive
    integer
  • At least one input is required
  • We cannot predict in advance how many illegal
    entries will occur
  • This may go on forever!
  • Scanner console
  • new Scanner(System.in)
  • int posInt0
  • while (posIntlt0)
  • System.out.print("Enter a positive number ")
  • posIntconsole.nextInt()

7
Error Infinite Loop
  • Congratulations on your new job!
  • Day 1 your wage is 1 penny
  • Each additional day your wage doubles
  • When can we party?
  • Can you spot the error?
  • //How to become a
  • //millionaire in a few days
  • double wage.01, netWorth0
  • int days0
  • while (netWorthlt1e6)
  • days 1 //count days
  • netWorth wage //payday
  • System.out.println( "Your net worth after
    " days " days is " netWorth)
  • wage 2 //double wage


Click to view animation steps
Animation Complete
8
Error Off By One
  • Calculating n factorial
  • n! 1 2 3 n
  • Initial values?
  • nfact 0 or 1?
  • Condition?
  • gt0, gt0?
  • Pre or Post Decrement?
  • --n or n
  • Decrement placement?
  • In the condition (--n gt 0) or in the
    multiplication?
  • //Calculate n!
  • static public int factorial(int n)
  • int nfact1 //the answer
  • while (n gt 0) nfact n--
  • return nfact

9
Do Loop
  • While is a pre-test loop
  • Loop condition is evaluated at the 'top' of the
    loop
  • Do (while) is a post-test Loop
  • Loop condition is evaluated at the bottom of the
    loop
  • Used when the loop body must be executed at least
    once
  • Used when the condition depends on the outcome of
    the calculations in the loop body

10
Do-While Syntax
  • do
  • statement
  • while (expression)
  • do
  • Statement list
  • while (expression)

xdice.roll()
!x.doubles()
true branch (iterate)
false branch (exit)
Keep rolling until you get doubles
11
Application Until
  • Retrieve coordinates from a map until the point
    is in quadrant 1
  • until xgt0 AND ygt0
  • The while condition is the negation of the until
    condition
  • while (!(xgt0 ygt0))
  • Apply DeMorgan's Law
  • while (xlt0 ylt0))
  • //First quadrant coordinates
  • double x, y
  • do
  • xdata.getAbscissa()
  • ydata.getOrdinate()
  • while (xlt0 ylt0)
  • System.out.println(
  • "("x","y") is in Quad 1"
  • )

12
For Loop
  • Combines the three fundamental parts of every
    loop
  • Initialization
  • Iteration control
  • Condition update
  • Most commonly used for count-controlled loops

13
For Syntax
int total0 int count1
  • for (exp1 exp2 exp3)
  • statement
  • for (exp1 exp2 exp3)
  • Statement list

count
countlt5?
true branch (iterate)
false branch (exit)
totaldice.roll()
Roll the dice 5 times
Click to view animation steps
Animation Complete
14
Application Sequences
  • Find the sum of the first 20 terms of the
    Fibonacci sequence
  • 11235
  • This is a common example of a counting loop
  • Notice that term is declared and initialized in
    the loop structure and is only defined for the
    life of the loop
  • //fib_a and fib_b are the previous
  • // two terms of the sequence
  • int fib_n, fib_a1, fib_b1
  • int sum2 //includes first 2 terms
  • for (int term3 termlt20 term)
  • fib_n fib_afib_b
  • sum fib_n
  • fib_a fib_b //keep only fib_b
  • fib_b fib_n // and fib_n
  • System.out.println("The sum is "sum)

15
Simple Bar Chart
  • //data comes from data object
  • for (xdata.next() //initialize
  • xgt0 //stop when data lt0
  • xdata.next()) //update
  • //row of x asterisks
  • for (int i0 iltx i)
  • System.out.print("")
  • //append row size
  • System.out.println("("x")")
  • (6)
  • (12)
  • (2)
  • (8)
  • These are nested loops
  • The outer loop iterates through the data values
  • The inner loop iterates to display the correct
    number of 's

16
Iterating For Input
  • Looping to process a list of input values is a
    common task
  • How can the looping process be controlled?
  • Count control
  • Know in advance how many inputs
  • Query control
  • Ask before each input if there are more values
  • Sentinel control
  • Continue reading data until a special value is
    encountered

17
Count Controlled Input
  • First data value is the number of items in the
    set
  • Common when data comes from a file
  • Not friendly when data is entered by a human
  • This example uses a Scanner named console
  • System.out.print("How many items? ")
  • int num console.nextInt()
  • for (int ct1 ctltnum ct)
  • System.out.print( "Enter next
    item ")
  • String data console.nextLine()//process
    input data

18
Query Controlled Input
  • Only used for interactive input
  • Requires the user to respond to a query before or
    after every input action
  • The example uses a Scanner named console and asks
    after each input
  • final String LOOP_RESP"y"
  • do
  • System.out.print("Input ")
  • String data console.nextLine()//process
    input data
  • System.out.print( "More data?
    (y/n) ")
  • while ( LOOP_RESP.equals(
  • console.nextLine())
  • //Loop terminates when input is
  • // NOT equal to
  • // LOOP_RESPONSE

19
Sentinel Controlled Input
  • Each input item can be either a data value to be
    processed or a special value that halts input
    (sentinel)
  • In this example, the value "" is used as the
    sentinel value
  • final String SENTINEL""
  • boolean isSentinelfalse
  • while(!isSentinel)
  • System.out.print("Input ")
  • String data console.nextLine()
  • if (data.equals(SENTINEL))
  • isSentinel true
  • else
  • //process input data
  • //Loop terminates when sentinel value is detected

20
Loop and a Half
  • boolean isSentinelfalse
  • while(!isSentinel)
  • System.out.print("Input ")
  • String data console.nextLine()
  • if (data.equals(SENTINEL))
  • isSentinel true
  • else
  • //process input data

isSentinelfalse
!isSentinel
dataconsole.nextLine()
data.equals(SENTINEL)?
//process data
isSentineltrue
Problem Iteration test occurs in the MIDDLE of
the loop
21
Priming Input
data is primed before loop
dataconsole.nextLine()
  • System.out.print("Input ")
  • String data console.nextLine()
  • while(!data.equals(SENTINEL))
  • //process input data
  • System.out.print("Input ")
  • data console.nextLine()

!data.equals( SENTINEL)
//process data
dataconsole.nextLine()
data is updated before condition is tested
22
Middle Of Loop Exit
  • while(true)
  • System.out.print("Input ")
  • String data console.nextLine()
  • if (data.equals(SENTINEL))
  • break //terminate loop
  • //process input data
  • //Loop exits from middle when sentinel is detected

//Branch never taken
true
true
dataconsole.nextLine()
true
data.equals(SENTINEL)?
break
//process data
Actual loop exit
23
Alternate Sentinel Control
  • Sentinel controlled input may be accomplished in
    the control expression
  • The value is assigned and tested against the
    sentinel in this single expression
  • This loop terminates naturally at the top
  • The loop body is all about processing data
  • The private method combines the prompt and input
    extraction actions
  • while(
  • !( data getInput(console) )
  • .equals(SENTINEL) )
  • //process input data
  • private String getInput(
  • Scanner con)
  • System.out.print("Input ")
  • return con.nextLine()

24
Character Access
  • Access to individual characters of a String is
    possible using the charAt method
  • aString.charAt(pos)
  • Iterating is commonly done with a for loop
  • Legal positions range from 0 through
    aString.length()-1
  • String s "3a5ru831T"
  • final String DGT"0123456789"
  • int dv, sum 0
  • for (int p0 plts.length() p)
  • //sum the digits in string
  • char x s.charAt(p)
  • if ((dvDGT.indexOf(x))gt0)
  • sum dv

25
Monte Carlo Simulations
  • Using random numbers to simulate events and make
    statistical inferences
  • Require the ability to access a sequence of
    random numbers
  • import java.util.Random
  • Random gennew Random()
  • The object gen is capable of producing random
    numbers on demand

This should execute only once in the life of your
program!
26
Robin Hood
  • Random coordnew Random()
  • int totalscores0
  • final int TRYS10000, ARROWS6, SIZE10
  • for (int trial0 trialltTRYS trial)
  • int score0
  • for (int shot0 shotltARROWS shot)
  • double x,y
  • xSIZE-coord.nextDouble()2SIZE
  • ySIZE-coord.nextDouble()2SIZE
  • double distMath.sqrt(xxyy)
  • if (distltSIZE) scoreSIZE-Math.floor(dist)
  • totalscoresscore
  • System.out.println( "Avg " (double)totalscores/
    TRYS )
  • Problem What is the expected score for 6 arrows
    shot at a target given that the archer always
    hits the target square (randomly)?
  • MC Solution
  • Generate 6 random 'hit' locations, total score
  • Do this many times and determine the average score

27
Summary
  • Java provides 3 basic looping structures
  • while, do-while, and for
  • Input loops can be controlled several ways
  • count, query, and sentinel control
  • The break statement can cause a middle-of-loop
    exit
  • The Random class can generate numbers that can be
    used in Monte Carlo simulations
Write a Comment
User Comments (0)
About PowerShow.com