Docsity

Understanding Recursive Functions: Self-Referential Formulas & Base Cases, Study notes of Computer Science

Partial preview of the text

Download Understanding Recursive Functions: Self-Referential Formulas & Base Cases and more Study notes Computer Science in PDF only on Docsity!

CSCE150A

Recursive Functions

Computer Science & Engineering 150A

Problem Solving Using Computers – Laboratory

Lecture 11 – Recursion

Derrick Stolee

Spring 2009

1 / 5^ [email protected]

CSCE150A

Recursive Functions

Sometimes, a function can refer to itself at a different value, to show its relation to smaller cases. Example: The function f (n) = 2n^ can be referred to as doubling the previous value, f (n − 1).

f (n) = 2n^ = 2 · 2 n−^1 = 2 · f (n − 1). Taking the self-referential formula as a definition, we call this recursion.

CSCE150A

Recursive Functions

Defining Recursion

We can use case notation to define a recursive function:

f (n) =

1 if n = 0 2 · f (n − 1) otherwise. This outlines how we can translate from a function into a program: (^1) Identify inputs (^2) Test for base cases – Return if found (^3) Otherwise – Return evaluation of recursive formula

CSCE150A

Recursive Functions

Programming Recursion

int f(int n) { if ( n == 0 ) { return 1; }

return 2*f(n-1); }