

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


with Java, for Beginners
CIS
1
Ā^
āRecursiveā means āself referencingā Ā^
When a class has an instance variable whose type isitself, we say it is ārecursively definedā. Itās an example ofāstructural recursionā. Ā^
Notice that the class has subparts that look like the whole.
Person
public class Person{
private String name;private Person mother;private Person father; }
CIS
2
Common Pattern:
public
type
foo(
parameters
if (
condition
return
value
else return foo(
arguments
CIS
3
Many things we model have recursive structures(where the subparts look like the whole):
Ā^
Mathematical formulasā¢
Power: x^y == x * x ^ (y-1)⢠Factorial: n! == n * (n-1)!⢠Fibonacci series: fib(n) == fib(n-1) + fib(n-2)⢠Fractal geometry (Julia, Mandelbrot sets) Ā^
Languagesā¢
Programming languages:
-^
An expression can contain expressions
-^
A statement can contain other statements
-^
HTML tags in a web page
-^
XML (extensible markup language), for storing semi-structured data
Ā^
Hierarchical Entities (often stored as ātreesā)ā¢
A āfamily ancestral treeā⢠An operating systemās folder/directory hierarchy Ā^
Graphsā¢
Social networks (Facebook)⢠Computer networks⢠Airline travel networks Recursive methods are frequently used to process such structures
CIS
4
Instead of having a loop, have it call itself
public static void countDown(int num){
if (num <= 0)
return; for (int i = num; i >= 1; i--){
System.out.println(num); } }
CIS
5
/ Recursive method that prints**
num, num-1, num-2, ... 1.
*** Assumes num is positive./public static void printDownTo1(int num){*
if (num == 0) // base case
return; System.out.println("num is " + num);printDownTo1(num - 1);
}
CIS
6
Handle the ābase caseā, which is when a recursive callshould
not
be made because the process should stop.
For other cases, make a recursive call (the recursiveāleap of faithā), which
must make progress towards a
goal
(towards the base case).
If the base case is not handled, or the recursive call doesnot progress towards the base case, then the method islikely to call itself infinitely (it will ādivergeā), and youāll get aāstack overrunā error.
CIS
7
public static int sum(int start, int end){
if (start > end) // base case
return 0; return start + sum(start + 1, end); }