Iteration

Exercise 1

Write a version of the procedure vector-sum using iteration.

Exercise 2

Using iteration, develop a Scheme procedure named max-of-vector that takes in a vector of numbers, and returns the largest number in that vector. You can assume that the vector has length at least 1.

Exercise 3

Write a version of the procedure Euclid-GCD using iteration.

Exercise 4

Write a version of the procedure Fibonacci using iteration.

Exercise 5

Using iteration, develop a Scheme procedure named prime? that takes a natural number, and returns #t if it is prime (is not divisible by any natural number other than itself or 1) and #f is if it is not.

Exercise 6

The rotate-vector! procedure presented in today's reading performs a ``circular right shift'' -- every element in the vector is shifted to the next higher-numbered position, except the last, which is moved to position 0. Develop a Scheme procedure that performs a circular left shift instead, moving every element of a given vector to the next lower-numbered position, except the element in position 0, which is moved to the last position.

Exercise 7

Develop a Scheme procedure that takes two vectors of equal length as arguments and returns a vector of Booleans, each element of which should be #t if the corresponding elements of the given vectors are identical (as determined by eqv?) and #f if they are not.

Exercise 8

Rewrite the definition of the vector-map! procedure, iterating with a do-expression instead of using the named let-expression to manage the recursion.

Exercise 9

Define a procedure Cartesian-square that takes any list ls as its argument and returns a list of pairs that contains every pair that can be formed from elements of ls (repetitions allowed).

> (Cartesian-square '(a b))
((a . a) (a . b) (b . a) (b . b))
> (Cartesian-square '(0 1 0))
((0 . 0) (0 . 1) (0 . 0) (1 . 0) (1 . 1) (1 . 0) (0 . 0) (0 . 1) (0 . 0))
> (Cartesian-square null)
()

This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~gum/courses/151/labs/iteration.xhtml

Validated as XHTML 1.1 by the World Wide Web Consortium Cascading Style Sheet validated by the World Wide Web Consortium

created April 12, 1997
last revised June 23, 2003

John David Stone (stone@cs.grinnell.edu)

Ben Gum (gum@cs.grinnell.edu)