Announcements: Assignment 5 is available to pick up at the end of class. It is due on October 18th (Saturday) at midnight. No lecture next Tuesday (fall break) No lab next Tuesday or Wednesday (fall break) but on Wednesday, TA/consultants will be in the lab room to help you with your assignment, etc. Read the 'timetable' on the first page of your assignment 5 for some important dates. Writing loops //Some discussion of loop invariants here Example 1: Let's consider a loop that computes the sum of even numbers 2..10 After each iteration: s = 2 s = 2+4 s = 2+4+6 . . s = 2+4+6+8+10 //invariant: p = sum of even numbers in range 2 through 2*k 4 Loopy questions: 1) How does it start? k = 0 s = 0 2) When does it stop? When k = 5 3) How does it make progress? k = k + 1 4) How does it fix the loop invariant? s = s+2*(k+1) int s = 0; int k = 0; //invariant: s = sum of even numbers in range 2 through 2*k while(k!=5){ s = s + 2*(k+1); k = k + 1; } Example 2: Given: //invariant: s = sum of k..13 //stops when k = 0 //initially, s = 0 What is k to make invariant true? 14 How does it end (given)? k = 0 How does it make progress? k = k - 1 How does it fix the invariant? s = s + (k-1) int s = 0; int k = 14; //invariant: s = sum of k..13 while(k!=0){ s = s + (k - 1); k = k - 1; } Example 3: Let's consider a loop that computes the sum of numbers from 3 to h (where h is a paramater). s = h = sum of h..h s = sum of h-1..h s = sum of h-2..h . . s = sum of 4..h s = sum of 3..h So, after the k-th iteration we have //invariant: s = sum of (h-k+1)..h Four loopy questions: 1) How does it start? (what values for k, s make invariant true?) k = 0 s = 0 2) When does it stop? (what value for k is the last one?) s = sum of 3..h when h-k+1 = 3, i.e. k = h-3+1 = h-2 3) How does it make progress? k = k + 1; 4) How does it fix the loop invariant? s = s + (h - k) int k = 0; int s = 0; //invariant: s = sum of (h-k+1)..h while(k != h-2){ s = s + (h - k); k = k + 1; } Example 4: Roach explosion, page 214.