General case: repeats over and over again
Base case: the way to return without making a recursive call
public static void ClimbStairs()
if (atTopOfStairs == true) // base case
done
else //general case
step up
ClimbStairs
Consider the sequence: 3, 6, 12, 24...
multiply the previous term by 2
Define mathematically:
$t_1 = 3$ (base case)
$t_n=t_{n-1}*2$ (general case), defined for $n >1$
Pseudocode:
calcTerm(n)
if n = 1 //base case
return 3
else //general case
return 2*calcTerm(n-1)
Determine $t_3$
//inside logic of the recursive method
calcTerm(3)
=2*calcTerm(2)
=2*(2*calcTerm(1))
=2*(2*3)
=2*(6)
=12
Java Code:
public static int calcTerm(int n){
if (n==1){ //base case
return 3;
}
else { //general case
return 2*calcTerm(n-1)
}
}
public static void main(String[]args){
System.out.println(calcTerm(1));
}