(JVM = Java Virtual Machine)
*currently called "permanent generation" storage in JVM
Sidetrip: Back to the 02A slides we didn't get to for some examples of this
An iterative (loop-based) approach (called on a Teacher object):
handOutPapers(pile): student = first student in line while pile is not empty: paper = pile.removeTop() give paper to student student = next student in line
A recursive approach (called on a Student object):
handOutPapers(pile): if pile is not empty: paper = pile.removeTop() keep paper next = next student in line next.handOutPapers(pile)
More descriptive of real life:
handOutPapers(pile): paper = pile.removeTop() keep paper if pile is not empty: next = next student in line next.handOutPapers(pile)
But in code: what if passed an empty pile?
handOutPapers(pile): if pile is not empty: paper = pile.removeTop() keep paper if pile is still not empty: next = next student in line next.handOutPapers(pile)
Original version was simpler. Often simplest code if you continue to 0 or empty case.
public class CodeD { public static void main(String[] args) { lotsAndLots(0); } public static void lotsAndLots(int num) { System.out.println(num); lotsAndLots(num + 1); } }
public static void printDigits(int n) { if (n == 0) { return; //base case: do nothing }else { System.out.println(n); printDigits(n - 1); //recursive call on smaller problem } }
else
?
public static void printDigits(int n) { if (n <= 0) { return; //base case: do nothing }else { printDigits(n - 1); //recursive call on smaller problem System.out.println(n); //print after returning from recursion } }
if
doesn't always have to be for base case
public static void printDigits(int n) { if (n <= 0) { return; //base case: do nothing } printDigits(n - 1); //recursive call on smaller problem System.out.println(n); //print after returning from recursion }
public static void printDigits(int n) { if (n > 0) { printDigits(n - 1); //recursive call on smaller problem System.out.println(n); //print after returning from recursion } //implied base case: do nothing if n <= 0. }
What if we want to generate a String of the numbers?
public static void main(String[] args) { String str = allDigits(4); System.out.println(str); } public static String allDigits(int n) { if (n <= 0) { return ""; }else { return n + " " + allDigits(n - 1); } }
public static int factorial(int n) { if (n <= 0) { return 1; }else { return n * factorial(n - 1); } }
Big-O?
/** Computes nth Fibonacci number: 1,1,2,3,5,8,13,... */ public static int fibonacci(int n) { if (n <= 0) { return 0; //error: n should not be less than 1 }else if (n <= 2) { return 1; }else { return fibonacci(n - 1) + fibonacci(n - 2); } }
Big-O?
public static int fibonacci(int n) { return fib(0, 1, n); } private static int fib(int prev, int curr, int n) { if (n <= 1) { return curr; }else { return fib(curr, prev + curr, n - 1); } }