# Recursion Tutorial

### From Progzoo

(Difference between revisions)

(→Factorial Function) |
(→Factorial Function) |
||

Line 15: | Line 15: | ||

else | else | ||

return i*fact(i-1); | return i*fact(i-1); | ||

+ | } | ||

+ | } | ||

+ | </prog> | ||

+ | 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 | ||

+ | </question> | ||

+ | |||

+ | |||

+ | ==What is the function== | ||

+ | |||

+ | <question class='P'> | ||

+ | <prog> | ||

+ | public class P{ | ||

+ | public static void main(String argv[]) | ||

+ | { | ||

+ | for (int i=0;i<5;i++) | ||

+ | System.out.printf("%d%8d\n",i,fact(i)); | ||

+ | } | ||

+ | |||

+ | static int f(int i){ | ||

+ | if (i==0) | ||

+ | return 1; | ||

+ | else | ||

+ | return i*f(i-1); | ||

} | } | ||

} | } |

## Revision as of 16:02, 9 February 2012

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

## 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]

## What is the function

Line: 123 DOMDocument::loadXML(): StartTag: invalid element name in Entity, line: 6