Download presentation
Presentation is loading. Please wait.
1
ITERATION CSC 171 FALL 2004 LECTURE 10
2
Simple Branching If (test){ A;} start end A; test
3
“Backward” Branching while(test){ A;} A; start end test
4
Example what is the output? int x = 3; int sum = 0; while (x > 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 < 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); x==0 x==2 x==0
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 TEST INVARIANT
12
Example Write a method to compute a n 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 (i>0){ 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 (i>0) { if (i%2 == 0) { b = b * b; i = i / 2;} else { r = r * b; i--; } } return r; }
15
Does it work? SURE! TRUST ME! Well, look at a 100 if you don’t believe me! – Note, less loops! Can you “prove” that it works? bir a1001 a2a2 50 a4a4 25 24a4a4 a8a8 12 a 16 6 a 32 3 2a 36 a 64 1 0a 100
16
What is the loop invariant? At the top of the while loop, it is true that r*b i = a n It is? – Well, at the top of the first loop r==1 b==a i==n
17
So, if it’s true at the start Even case r new = r old b new == (b old ) 2 i new ==(i old )/2 Therefore, r new * (b new ) inew == r old * ((b old ) 2 ) iold/2 == r old * (b old ) iold == a n
18
So, if it’s true at the start II Odd case r new = r old *b old b new == b old i new ==i old -1 Therefore, r new * (b new ) inew == r old *b old * (b old ) iold-1 == r old * (b old ) iold == a n
19
So, If it’s true at the start And every time in the loop, it remains true Then, it is true at the end r*b i = a n 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; start end test
25
“Backward” Branching do { A; }while (test); A; start end test
26
YOU WRITE THE CODE start end y < 3 X = 1; y = 1; X = 2 * x; y++;
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; } Problems here are caught here
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 it’s own syntax
31
TYPES OF ITERATION Indefinite Iteration: – We don’t 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 < 2 * initialBalance){ balance += balance * interest; year++; }
34
Example of a “for” loop as a while int count ; count = 0; while(count < 10) { A;count++;} A; start end count<10 count++ count=0
35
Example of a “for” loop as a for for(int count = 0; ;count < 10; ;count < 10; count++;) { count++;) {A;} A; start end count<10 count++ count=0
36
Generic “for” loop for(init; test ; update;) { update;) {body;} body; start end test update init
37
For loop
38
For loop Code for (int year = 1;year<=20;year++){ balance += balance * interest; }
39
For Loop Initialization Test Body Increment for(initialzation;test;increment){ //Body }
40
Off by one errors If you want n iterations Start at 0 and go to x < n Or Start at 1 and go to x <= 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 ; i<size;i++) { for(int j = 0 ; j<size;j++) { System.out.println(String.toString(i*j)); }
43
Multiplication Table Fixed int size = 5; for(int i = 0 ; i<size;i++) { for(int j = 0 ; j<size;j++) { System.out.print(String.toString(i*j) + “ “); } 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 aren’t 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); } }}}}
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.