ITERATION - PowerPoint PPT Presentation

About This Presentation
Title:

ITERATION

Description:

System.out.print('x == ' x); System.out.println('sum == ' sum) ... Then appears to 'hang' Shorthand Operators. a = a b ; a = a b; a = a * b; a = a / b; ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 50
Provided by: thaddeusf
Category:
Tags: iteration | hang

less

Transcript and Presenter's Notes

Title: ITERATION


1
ITERATION
  • CSC 171 FALL 2004
  • LECTURE 10

2
Simple Branching
If (test) A
3
Backward Branching
while(test) A
A
4
Example what is the output?
  • int x 3
  • int sum 0
  • while (x gt 0)
  • sum sum x
  • x x 1
  • System.out.print(x x)
  • System.out.println(sum sum)

x 3, sum 0
x 2, sum 3
x 1, sum 5
x 0, sum 6
5
Example what is the output?
  • int x 3
  • int sum 0
  • while (x lt 5)
  • sum sum x
  • x x 1
  • System.out.print(x x)
  • System.out.println(sum sum)

x 3, sum 0
x 2, sum 3
x 1, sum 5
x 0, sum 6
x -1, sum 6
6
Infinite Loops
  • A very common fault in program design
  • System compiles ok
  • Then appears to hang

7
Shorthand Operators
  • a a b
  • a a b
  • a a b
  • a a / b
  • a a b
  • a b
  • a - b
  • a b
  • a / b
  • a b

8
More Shorthand
  • int x
  • x x 1
  • x 1
  • x x 1
  • x - 1
  • x
  • x--

9
Shorthand Operators x vs. x
  • int x 0
  • System.out.println(x x)
  • System.out.println(x x)
  • System.out.println(x x--)
  • System.out.println(x --x)

x0
x2
x2
x0
10
Loop invariants
  • Intro to mathematical program analysis
  • In order to verify loops we often establish an
    assertion (boolean expression) that is true each
    time we reach a specific point in the loop.
  • We call this assertion, a loop invariant

11
Assertions
  • When ever the program reaches the top of the
    while loop, the assertion is true

INIT
BODY
INVARIANT
TEST
12
Example
  • Write a method to compute an
  • public static int power(int a , int n)
  • Positive values only ok
  • You have 5 minutes

13
Possible solution
  • public static int power(int a, int n)
  • int r 1 int b a int i n
  • while (igt0)
  • r b
  • return r

14
Possible solution (Euclid)
  • public static double power(int a, int n)
  • int r 1 int b a int i n
  • while (igt0)
  • if (i2 0) b b b i i / 2
  • else r r b i--
  • return r

15
Does it work?
  • SURE! TRUST ME!
  • Well, look at a100 if you dont believe me!
  • Note, less loops!
  • Can you prove that it works?

16
What is the loop invariant?
  • At the top of the while loop, it is true that
  • rbi an
  • It is?
  • Well, at the top of the first loop
  • r1
  • ba
  • in

17
So, if its true at the start
  • Even case
  • rnew rold
  • bnew (bold)2
  • inew(iold)/2
  • Therefore,
  • rnew (bnew)inew rold ((bold)2)iold/2
  • rold
    (bold)iold
  • an

18
So, if its true at the start II
  • Odd case
  • rnew roldbold
  • bnew bold
  • inewiold-1
  • Therefore,
  • rnew (bnew)inew rold bold (bold)iold-1
  • rold
    (bold)iold
  • an

19
So,
  • If its true at the start
  • And every time in the loop, it remains true
  • Then, it is true at the end
  • rbi an
  • And, i 0 ( the loop ended)
  • What do we know?

20
Correctness Proofs
  • Proof are more valuable than testing
  • Tests demonstrate limited correctness
  • Proofs demonstrate correctness for all inputs
  • For some time, people hoped that all formal logic
    would replace programming
  • The naïve idea that programming is a form of
    math proved to be an oversimplification

21
Correctness Proofs
  • Unfortunately, in practice, these methods never
    worked very well.
  • Instead of buggy programs,
  • people wrote buggy logic
  • Nonetheless, the approach is useful for program
    analysis

22
The take away message?
  • In the end, engineering and (process) management
    are at least as important as mathematics and
    logic for the successful completion of large
    software projects

23
Do while
  • A useful variant of the while loop

24
Backward Branching
while(test) A
A
25
Backward Branching
do A while (test)
26
YOU WRITE THE CODE
start
X 1 y 1
X 2 x y
y lt 3
end
27
Use of a sentinel
  • A variable that keeps track of the ending
    condition

28
Example
  • static int myGetInt()
  • boolean done false
  • String locIn ""
  • int returnVal 0
  • InputStreamReader reader
  • new InputStreamReader(System.in)
  • BufferedReader console
  • new BufferedReader(reader)

//sentinal
29
  • do
  • try
  • locIn console.readLine()
  • returnValue Integer.ParseInt(locIn)
  • done true
  • catch (Exception e)
  • System.out.println(e trouble")
  • done false
  • while (!done)
  • return returnVal

30
For loops
  • Sometimes, we want the loop to repeat for a set
    (definite) number of times.
  • A type of while loop
  • That became so common
  • It was given its own syntax

31
TYPES OF ITERATION
  • Indefinite Iteration
  • We dont know exactly how many times we want the
    loop to repeat
  • while loop
  • Definite Iteration
  • We know how many time we want the loop to repeat
  • for loop

32
While loop
33
While loop Code
  • int year 0
  • while (balance lt 2 initialBalance)
  • balance balance interest
  • year

34
Example of a for loop as a while
start
int count count 0 while(count lt 10)
A count
count0
count
A
end
35
Example of a for loop as a for
start
for(int count 0 count lt 10 count)
A
count0
count
A
end
36
Generic for loop
start
for(init test update) body
init
update
body
end
37
For loop
38
For loop Code
  • for (int year 1yearlt20year)
  • balance balance interest

39
For Loop
  • Initialization
  • Test
  • Body
  • Increment
  • for(initialzationtestincrement)
  • //Body

40
Off by one errors
  • If you want n iterations
  • Start at 0 and go to x lt n
  • Or
  • Start at 1 and go to x lt n

41
Nested Loops
  • Sometimes, we want to perform 2D operations
  • Tables
  • Addition
  • Multiplication
  • Interest rates

42
Multiplication Table
  • What is the output?
  • int size 5
  • for(int i 0 iltsizei)
  • for(int j 0 jltsizej)
  • System.out.println(String.toString(ij))

43
Multiplication Table Fixed
  • int size 5
  • for(int i 0 iltsizei)
  • for(int j 0 jltsizej)
  • System.out.print(String.toString(ij) )
  • System.out.println()

44
Enumerations
  • Integers are nice, because we always have a clear
    idea of what the next one is.
  • But sometimes, we have an orderd set or list of
    things that arent numbers
  • Hearts, Spades, Diamonds, Clubs
  • Bob, Carol, Ted, Alice
  • We would like to go through them one at a time

45
public interface Enumeration
  • An object that implements the Enumeration
    interface generates a series of elements, one at
    a time. Successive calls to the nextElement
    method return successive elements of the series.
  • For example, to print all elements of a vector v

46
General Case
  • Enumeration e
  • while(e.hasMoreElements()) System.out.println(e
    .nextElement())

47
Our Fave StringTokenizer
  • A String Tokenizer breaks strings up into tokens
    (surprize!)
  • String Hello CSC 171, How are you
  • Tokens
  • Hello,CSC,171,,How,are,you
  • StringTokenizer tokenizer
  • new StringTokenizer(inputLine)

48
Using String Tokenizer
  • import java.util.StringTokenizer
  • public class Split
  • public static void main(String args)
  • boolean done false
  • while (!done)
  • String inputLine myGetString()
  • if (inputLine null) done true
  • else
  • // break input line into words

49
String Tokeizer II
  • StringTokenizer tokenizer
  • new StringTokenizer(inputLine)
  • while (tokenizer.hasMoreTokens())
  • String word tokenizer.nextToken()
  • System.out.println(word)
Write a Comment
User Comments (0)
About PowerShow.com