Topic

Chapter

## Recursion

Under Tags :

Share This Topic -

**Recursion :**

Recursion is the process of defining something in terms of itself.

When function call it self is called recursion.

A method that calls itself is said to be recursive.

**EX :**

import java.util.Scanner; class Factorial { // this is a recursive function int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; //From here function call it self (fact(n-1)) return result; } } public class Recursion { public static void main(String args[]) { int x; Scanner s = new Scanner(System.in); System.out.print("Enter int no = "); x = s.nextInt(); Factorial f = new Factorial(); System.out.println("Factorial of" + x + " is " + f.fact(x)); } }

**Output :**

Enter int no = 7

Factorial of7 is 5040

Here the method fact is recursive because it calls itself.

The whole precess something like this

result = fact(7-1) * 7 and so on until it returns 1.

So one thing is sure that we have to take care that in every recursive process there must be a terminate condition to come out from recursion.