Recursion Tutorial

From Progzoo

(Difference between revisions)
(What is the function)
(What is the function)
 
Line 76: Line 76:
 
   public static void main(String argv[])
 
   public static void main(String argv[])
 
   {
 
   {
     for (int i:int[]{2, 42, 111, 2753})
+
     for (int i:new int[]{2, 42, 111, 2753})
       System.out.printf("%d%8d\n",i,f(i));
+
       System.out.printf("%5d%8d\n",i,f(i));
 
   }
 
   }
  
Line 84: Line 84:
 
       return 0;
 
       return 0;
 
     else
 
     else
       return (i%10)f(i/10);
+
       return (i%10)+f(i/10);
 
   }
 
   }
 
}
 
}
 +
 +
 
]]></prog>
 
]]></prog>
 
</question>
 
</question>

Latest revision as of 15:08, 9 February 2012

Recursive functions typically have a base case and a recursive case.

Contents

[edit] Factorial Function

The function fact takes a single integer input. The result is that number times by each of the numbers smaller - down to one.

fact(1) =   1         =   1
fact(2) =   1*2       =   2
fact(3) =   1*2*3     =   6
fact(4) =   1*2*3*4   =  24
fact(5) =   1*2*3*4*5 = 120

[Font] [Default] [Show] [Resize] [History] [Profile]


[edit] What is the function


[Font] [Default] [Show] [Resize] [History] [Profile]


[edit] What is the function


[Font] [Default] [Show] [Resize] [History] [Profile]

[edit] What is the function


[Font] [Default] [Show] [Resize] [History] [Profile]