0% found this document useful (0 votes)
11 views

Recursion: Public Static Void Foo (Int X) (If (X 0) Foo (X / 2) System - Out.println (X % 2) )

Recursion is a process where a method calls itself repeatedly. A recursive method requires a base condition to stop the recursion and a pattern that is repeated in each recursive call. For example, a recursive method to calculate a factorial has a base case of 1 for 0! and a pattern of multiplying the number by the factorial of the previous number.

Uploaded by

prof_kt
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Recursion: Public Static Void Foo (Int X) (If (X 0) Foo (X / 2) System - Out.println (X % 2) )

Recursion is a process where a method calls itself repeatedly. A recursive method requires a base condition to stop the recursion and a pattern that is repeated in each recursive call. For example, a recursive method to calculate a factorial has a base case of 1 for 0! and a pattern of multiplying the number by the factorial of the previous number.

Uploaded by

prof_kt
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Recursion Recursion is the process of calling one's self, that is, inside a method the method calls itself.

For example:
public static void foo(int x) { if( x > 0) foo(x / 2); System.out.println(x % 2); }

All recursive routines must have the following: Base condition Pattern The base condition is when the recursion terminates, when the method stops calling itself. The recursive calling must stop at some point, otherwise you will have an infinite recursion (like an infinite loop). There must be some pattern that is repeated that can be reproduced in the code. For example to write a recursive method to compute the factorial of a number (4! = 4321), we define the base case: F(0) = 1 and the pattern to be: F(n) = n F(n-1) We can translate this to the Java method:
public static int fact(int n) { if (0 == n) return 1; else return n * fact(n-1); }

You might also like