Title: ITERATION
1ITERATION
- CSC 171 FALL 2004
- LECTURE 10
2Simple Branching
If (test) A
3Backward Branching
while(test) A
A
4Example 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
5Example 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
6Infinite Loops
- A very common fault in program design
- System compiles ok
- Then appears to hang
7Shorthand Operators
- a a b
- a a b
- a a b
- a a / b
- a a b
8More Shorthand
- int x
- x x 1
- x 1
- x x 1
- x - 1
9Shorthand 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
10Loop 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
11Assertions
- When ever the program reaches the top of the
while loop, the assertion is true
INIT
BODY
INVARIANT
TEST
12Example
- Write a method to compute an
- public static int power(int a , int n)
- Positive values only ok
- You have 5 minutes
13Possible solution
- public static int power(int a, int n)
- int r 1 int b a int i n
- while (igt0)
- r b
-
- return r
14Possible 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
15Does it work?
- SURE! TRUST ME!
- Well, look at a100 if you dont believe me!
- Note, less loops!
- Can you prove that it works?
16What 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
17So, 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
18So, 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
19So,
- 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?
20Correctness 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
21Correctness 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
22The 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
23Do while
- A useful variant of the while loop
24Backward Branching
while(test) A
A
25Backward Branching
do A while (test)
26YOU WRITE THE CODE
start
X 1 y 1
X 2 x y
y lt 3
end
27Use of a sentinel
- A variable that keeps track of the ending
condition
28Example
- 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
30For 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
31TYPES 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
32While loop
33While loop Code
- int year 0
- while (balance lt 2 initialBalance)
- balance balance interest
- year
-
34Example of a for loop as a while
start
int count count 0 while(count lt 10)
A count
count0
count
A
end
35Example of a for loop as a for
start
for(int count 0 count lt 10 count)
A
count0
count
A
end
36Generic for loop
start
for(init test update) body
init
update
body
end
37For loop
38For loop Code
- for (int year 1yearlt20year)
- balance balance interest
-
39For Loop
- Initialization
- Test
- Body
- Increment
- for(initialzationtestincrement)
- //Body
40Off 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
41Nested Loops
- Sometimes, we want to perform 2D operations
- Tables
- Addition
- Multiplication
- Interest rates
42Multiplication Table
- What is the output?
- int size 5
- for(int i 0 iltsizei)
- for(int j 0 jltsizej)
- System.out.println(String.toString(ij))
-
43Multiplication Table Fixed
- int size 5
- for(int i 0 iltsizei)
- for(int j 0 jltsizej)
- System.out.print(String.toString(ij) )
-
- System.out.println()
44Enumerations
- 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
45public 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
46General Case
- Enumeration e
- while(e.hasMoreElements()) System.out.println(e
.nextElement()) -
47Our 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)
48Using 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
49String Tokeizer II
- StringTokenizer tokenizer
- new StringTokenizer(inputLine)
- while (tokenizer.hasMoreTokens())
- String word tokenizer.nextToken()
- System.out.println(word)
-