Transcript Document 7716619
CMSC 203 / 0201 Fall 2002
Week #7 – 7/9/11 October 2002 Prof. Marie desJardins
September1999
TOPICS
Recursion Recursive and iterative algorithms Program correctness
October 1999 September1999
MON 10/7 RECURSION (3.3)
September1999
Concepts/Vocabulary
Recursive (a.k.a. inductive) function definitions Recursively defined sets Special sequences: Factorial F(0)=1, F(n) = F(n-1) (n) = n!
Fibonacci numbers f 0 = 0, f 1 = 1, f n = f n-1 Strings *: Strings over alphabet Empty string String length l(s) String concatenation + f n-2
September1999 October 1999
Examples
S 1 = Even positive integers 2 S 1 ; x+2 S 1 if x S 1 S 2 = Even integers 2 S 2 ; x+2 S 2 if x S 2 ; x-2 S 2 if x S 2 Prove that S 1 is the set of all even positive integers Every even positive integer is in S 1 … Every member of S 1 is an even positive integer…
September1999 October 1999
Examples II
Exercise 3.3.5: Give a recursive definition of the sequence {a n }, n = 1, 2, 3, … if (a) a n = 6n (b) a n = 2n + 1 (c) a n = 10 n (d) a n = 5 Exercise 3.3.31: When does a string belong to the set A of bit strings defined recursively by 0
x
1 A if x A, where is the empty string?
September1999 October 1999
Examples III
Exercise 3.3.33: Use Exercise 29 [definition of w i ] and mathematical induction to show that l(w i ) = i l(w), where w is a string and i is a nonnegative integer.
Exercise 3.3.34: Show that (w R ) I = (w i ) R whenever w is a string and I is a nonnegative integer; that is, show that the ith power of the reversal of a string is the reversal of the ith power of the string.
September1999 October 1999
WED 10/9 RECURSIVE ALGORITHMS (3.4)
** HOMEWORK #4 DUE ** ** UNGRADED QUIZ TODAY **
September1999
Concepts / Vocabulary
Recursive algorithm Iterative algorithm
October 1999 September1999
Examples
Algorithm 7: Recursive Fibonacci Complexity of f 7 (Exercise 14), f n Algorithm 8: Iterative Fibonacci Complexity f 7 (Exercise 14), f n Eercise 3.4.23: Give a recursive algorithm for finding the reversal of a bit string.
September1999 October 1999
FRI 10/11 PROGRAM CORRECTNESS (3.5)
September1999
Concepts / Vocabulary
Initial assertion, final assertion Correctness, partial correctness, termination “Partially correct with respect to initial assertion p and final assertion q” Rules of inference Composition rule Conditional rules Loop invariants
September1999 October 1999
Examples
Exercise 3.5.3: Verify that the program segment x := 2 z := x + y if y > 0 then z := z + 1 else z := 0 is correct with respect to the initial assertion y=3 and the final assertion z=6.
September1999 October 1999
Examples II
Exercise 3.5.6: Use the rule of inference developed in Exercise 5 [if… else if … else …] to verify that the program if x < 0 then y := -2|x| / x else if x > 0 then y := 2|x| / x else if x = 0 then y := 2 is correct with respect to the initial assertion
T
the final assertion y=2.
and
September1999 October 1999