SUNY Geneseo Department of Computer Science
{Date}
CSci 141, Fall 2003
Prof. Doug Baldwin
6.3.1 Guiseppe Peano's axioms
Read Sections 6.2 - 6.4
Recursion going towards smaller problem
Index = part of algorithm (or parameter) responsible for going towards smaller problem.
Problems:
Recursion can also be value-producing
Termination
if ( C1 && C2 )
base case
else
recursive case
Design a recursive algorithm, int powerOf2( int n )
, that computes
and returns 2n
if n >= 0
for ( n = n; 2 * n; n-- )
sum = 2*n + sum
return sum
How about
int powerOf2( int n )
if n = 0
return 1
if n >= 1
sum = sum * 2
powerOf2( n-1 )
return sum
if n <= -1
sum = sum * 2
powerOf2( n+1 )
return 1/sum
or...
int powerOf2( int n )
if n = 0
return 1
if n >= 1
return 2 * powerOf2( n-1 )
if n <= -1
return (1 / 2) * powerOf2( n+1 )
Some more sophisticated uses of recursion
Read Section 6.5
Mini-Assignment: Design a recursive algorithm that makes a robot draw an n-tile line and then go back to its original tile.