Advertisement
yo2man

Tutorial 44 Recursion: A Useful Trick Up Your Sleeve

May 25th, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. //Tutorial 44 Recursion: A Useful Trick Up Your Sleeve
  2. //simple
  3. public class App {
  4.  
  5.     public static void main(String[] args) {
  6.        
  7.         //E.g. 4! = 4*3*2*1
  8.         System.out.println(factorial(5));
  9.     }
  10.     private static int factorial(int value) {
  11.         System.out.println(value); //5, 4, 3, 2, 1
  12.    
  13.         if(value == 1) { //this to stop the continuos recursion to infinitey/StackOverflow, stop at the value of 1
  14.             return 1;
  15.         }
  16.         return factorial(value - 1) * value; //the factorial (#)! (ie: 5 *3*2*1 = 120)
  17.        
  18.     }
  19. }
  20.  
  21.  
  22. //---------------------------------------------------------------------------------------------------------------------------------------
  23. /* Run Results:
  24. 5
  25. 4
  26. 3
  27. 2
  28. 1
  29. 120
  30. */
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37. //---------------------------------------------------------------------------------------------------------------------------------------
  38. //Practice
  39. public class App {
  40.  
  41.     public static void main(String[] args) {
  42.         System.out.println(calculate(7));
  43.     }
  44.     private static int calculate(int value) {
  45.         System.out.println(value);
  46.    
  47.         if(value == 1) {
  48.             return 1;
  49.         }
  50.     return calculate(value - 1) * value;
  51.     }
  52. }
  53.  
  54. /* Run Results:
  55. 7
  56. 6
  57. 5
  58. 4
  59. 3
  60. 2
  61. 1
  62. 5040
  63. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement