

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to recursion in java programming, explaining the concept of self-referencing and its applications in various structures such as mathematical formulas, languages, hierarchical entities, and graphs. It includes examples of recursive methods and a recursion recipe for writing recursive methods.
Typology: Study notes
1 / 3
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); }