CS109A Notes For Lecture 1/19/96 Recursive Denition of Expressions Basis: Induction
CS109A Notes For Lecture 1/19/96 Recursive Denition of Expressions Basis: Induction
Induction:
o E
x
x
( + )
( + )
An Interesting Proof
;S
>
;:::;S n
E
S n
o E
length E
length E
;:::;S n
Recursion
A style of programming and problem-solving
where we express a solution in terms of
smaller instances of itself.
Uses basis/induction just like inductive proofs
and de nitions.
Basis = part that requires no uses of
smaller instances.
Induction = solution of arbitrary instance in terms of smaller instances.
Why Recursion?
Example: A simple algorithm for converting integer 0 to binary: Last bit is %2; leading bits
determined by converting 2 until we get down to
0.
i >
i=
main() {
int i;
scanf("%d", &i);
while(i>0) {
putchar('0' + i%2);
i /= 2;
}
putchar('\n');
}
>
i=
void convert(int i) {
if(i>0) {
convert(i/2);
putchar('0' + i%2);
}
}
main() {
int i;
scanf("%d", &i);
convert(i);
putchar('\n');
}