Recursion: Public Static Void Foo (Int X) (If (X 0) Foo (X / 2) System - Out.println (X % 2) )
Recursion: Public Static Void Foo (Int X) (If (X 0) Foo (X / 2) System - Out.println (X % 2) )
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); }