Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 44 Recursion: A Useful Trick Up Your Sleeve
- //simple
- public class App {
- public static void main(String[] args) {
- //E.g. 4! = 4*3*2*1
- System.out.println(factorial(5));
- }
- private static int factorial(int value) {
- System.out.println(value); //5, 4, 3, 2, 1
- if(value == 1) { //this to stop the continuos recursion to infinitey/StackOverflow, stop at the value of 1
- return 1;
- }
- return factorial(value - 1) * value; //the factorial (#)! (ie: 5 *3*2*1 = 120)
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- /* Run Results:
- 5
- 4
- 3
- 2
- 1
- 120
- */
- //---------------------------------------------------------------------------------------------------------------------------------------
- //Practice
- public class App {
- public static void main(String[] args) {
- System.out.println(calculate(7));
- }
- private static int calculate(int value) {
- System.out.println(value);
- if(value == 1) {
- return 1;
- }
- return calculate(value - 1) * value;
- }
- }
- /* Run Results:
- 7
- 6
- 5
- 4
- 3
- 2
- 1
- 5040
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement