ITERATION CSC 171 FALL 2004 LECTURE 10
Simple Branching If (test){ A;} start end A; test
“Backward” Branching while(test){ A;} A; start end test
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
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 ……
Infinite Loops A very common fault in program design System compiles ok Then appears to “hang”
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;
More Shorthand int x; x = x + 1; x += 1; x = x – 1; x -= 1; x++; x-- ;
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
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
Assertions When ever the program reaches the top of the while loop, the assertion is true INIT BODY TEST INVARIANT
Example Write a method to compute a n public static int power(int a, int n) Positive values only ok You have 5 minutes
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; }
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; }
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 a4a a4a4 a8a8 12 a 16 6 a a 36 a a 100
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
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
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
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?
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
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
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
Do while A useful variant of the while loop
“Backward” Branching while(test){ A;} A; start end test
“Backward” Branching do { A; }while (test); A; start end test
YOU WRITE THE CODE start end y < 3 X = 1; y = 1; X = 2 * x; y++;
Use of a sentinel A variable that “keeps track” of the ending condition
Example static int myGetInt() { boolean done = false; String locIn = ""; int returnVal = 0; InputStreamReader reader = new InputStreamReader(System.in); BufferedReader console = new BufferedReader(reader); //sentinal
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
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
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
While loop
While loop Code int year = 0 ; while (balance < 2 * initialBalance){ balance += balance * interest; year++; }
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
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
Generic “for” loop for(init; test ; update;) { update;) {body;} body; start end test update init
For loop
For loop Code for (int year = 1;year<=20;year++){ balance += balance * interest; }
For Loop Initialization Test Body Increment for(initialzation;test;increment){ //Body }
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
Nested Loops Sometimes, we want to perform 2D operations Tables – Addition – Multiplication – Interest rates
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)); }
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(); }
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
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:
General Case Enumeration e ; while(e.hasMoreElements()) { System.out.println(e.nextElement( )); }
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);
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
String Tokeizer II StringTokenizer tokenizer = new StringTokenizer(inputLine); while (tokenizer.hasMoreTokens()){ String word = tokenizer.nextToken(); System.out.println(word); } }}}}