Last active
December 14, 2015 22:18
-
-
Save raineorshine/5156886 to your computer and use it in GitHub Desktop.
Java: Simple Recursion Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RecursionTest | |
{ | |
public static int calc(int n) | |
{ | |
// base case | |
if(n == 0) | |
{ | |
return 1; | |
} | |
/* | |
recursive case | |
Point 1: The recursive call puts the current function "on pause" | |
Point 2: Every function call maintains its own copy of local vars | |
Point 3: After the base case has been hit, each function that is | |
"on pause" needs to return before the original call returns. | |
*/ | |
int temp = 10 + calc(n-1); | |
return temp; | |
} | |
public static void main(String[] args) | |
{ | |
int result = calc(2); // kicks off the recursive function | |
System.out.println(result); // prints 21 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment