Home » Java programming language

Explain recursion in Java with an Example

In this article, we are going to learn: what is recursion and how to implement recursion in java?

Just like C and C++ programming language, java also supports recursion. Recursion is a process by a function calls itself recursively.

In terms of Java programming, recursion is the process that allows a method to call itself.

Consider the example:
In this example, we are calculating factorial of a given number. Suppose, there is a number 5 then its factorial would be 1x2x3x4x5 = 120. And factorial will be calculated through recursion function.

class Factorial
{
	//Recursion method
	int fact(int num)
	{
		int result;
		//if/when num is 1
		if(num==1) 
			return 1;
		//calling method itself
		result = fact(num-1) * num;
		return result;
	}
}

public class ExampleRecursion 
{
	public static void main(String args[]) 
	{
		Factorial factMethod = new Factorial();
		System.out.println("Factorial of 1 is: " + factMethod.fact(1));
		System.out.println("Factorial of 2 is: " + factMethod.fact(2));
		System.out.println("Factorial of 3 is: " + factMethod.fact(3));
		System.out.println("Factorial of 4 is: " + factMethod.fact(4));
		System.out.println("Factorial of 5 is: " + factMethod.fact(5));
	}
}

Output

Factorial of 1 is: 1
Factorial of 2 is: 2
Factorial of 3 is: 6
Factorial of 4 is: 24
Factorial of 5 is: 120


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.