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

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.