In this tutorial, we will discuss the concept of Recursion in the Java programming language.
In this post, we will learn about the recursive method and how it functions in Java.
We have already discussed recursive function in C language, C++ and Python language.
Recursion is a technique in Programming languages. In Java, a method that calls on itself is called a recursive method (same concept of recursive function in C, C++ and Python);
The flow of control of recursive function:
The diagram shows how recursion works:
In the above diagram, initially, recursive() method is called from the inside of the main method (looks like a normal method call).
The recursive() method is called from the inside the same method (it called itself),
The recursion follows until a condition is fulfilled.
Program 1
class Find_Fact{ static int factorial(int num){ if (num!=0) return num*factorial(num-1); //recursive call else return 1; } public static void main(String args[]){ int number=5,fact; fact=factorial(number); System.out.println("Factorial of "+number+" is "+fact); } }
When the above code is executed, it produces the following results
Factorial of 4 is 24
In the above program, first, the factorial() method is called from inside the main method and also argument is passed.
When the value is passed to the function, it is stored in the num variable.
Initially, the argument is passed thus the value of num is 4. Then the method calls on itself which reduces the value of num by 1 and it becomes 3. Then, it passes on during the next recursive call of “factorial()” function. subsequently, it continues to reduce by one in every stage until it becomes 1.
When the num variable becomes less then 1, “if condition” returns as false and flow of control moves to Else part for execution.
once Else part executes, it excludes itself from the function.
The following picture shows how the above program is functioning
Easy to understand, readable code and reduced number of lines in the program.
This recursion makes complex tasks easy and flexible. Also, repeated functioning is easier following iterations.
Tracing and debugging are very difficult.
Every recursive step lacks a separate memory location hence extra memory is required process (becomes very slow).
Similar post
Suggested for you
C# inverted full pyramid star pattern In this article, we will discuss the concept of…
C# Full Pyramid star pattern program In this article, we will discuss the concept of…
Program to count vowels, consonants, words, characters and space in Java In this article, we…
How to print multiplication table using Array in C++ language In this post, we will…
C Program to multiplication table using Array In this tutorial , we will discuss about…
Java program to check odd or even using recursion In this tutorial, we discuss a…