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

Recursion

Recursion in Java refers to a method that calls itself. This technique is known as recursion. A recursive method calls itself until a condition is met to end the recursion, otherwise infinite recursion occurs. For example, a factorial method is defined recursively to return the factorial of a number by multiplying it by the factorial of the number minus one. Recursion uses more memory than iterative solutions as each call allocates new storage, but recursive solutions are simpler to write and maintain.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Recursion

Recursion in Java refers to a method that calls itself. This technique is known as recursion. A recursive method calls itself until a condition is met to end the recursion, otherwise infinite recursion occurs. For example, a factorial method is defined recursively to return the factorial of a number by multiplying it by the factorial of the number minus one. Recursion uses more memory than iterative solutions as each call allocates new storage, but recursive solutions are simpler to write and maintain.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

RECURSION IN JAVA

 A method that calls itself is known as a recursive method.


And, this technique is known as recursion.
 How recursion works?
 Public static void main(String args[]){
………….
recurse()
… ….. …..
}
Static void recurse() {
recurse()
}
 In the above program, recurse() method is called from inside the
main method at first (normal method call).
 Also, recurse() method is called from inside the same
method, recurse(). This is a recursive call.
 The recursion continues until some condition is met to prevent it
from execution. If not, infinite recursion occurs.
 Hence, to prevent infinite recursion, if...else statement (or
similar approach) can be used where one branch makes the
recursive call and other doesn't.
class Factorial {

static int factorial( int number ) {


if (number != 0)
return number * factorial(number-1); // recursive call
else
return 1;
}

public static void main(String[] args) {


int number = 4, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}
Advantages and Disadvantages of Recursion
 When a recursive call is made, new storage location for variables
are allocated on the stack.
 As, each recursive call returns, the old variables and parameters
are removed from the stack. Hence, recursion generally use more
memory and are generally slow.
 On the other hand, recursive solution is much simpler and takes
less time to write, debug and maintain.

You might also like