# Top 5 Recursive Problem-Solving Examples In Java

Hello there!

This article investigates five excellent instances of recursive programming in Java. We dig deep into the logic that powers the process, the syntax & semantics that bring the logic to life, and investigate possible ways of improving the time & space complexity of recursive methods.

But, before we do that, let’s recap the concepts of recursion in Java.

**Using Recursion In Java**

Simply put, recursion involves designing a process that repeats itself. Recursive codes call or execute themselves and can solve specific problem scenarios better than loops or iterations. Recursive codes are concise, elegant, simple, and sweet, unlike their iterative counterparts!

Recursion is a popular technique to perform sequential operations in many programming languages. Developing recursion programming logic instead of loops leads to faster execution, lower memory consumption, and fewer bugs.

- Recursion is a natural approach to many problems and lies at the heart of
*dynamic programming.* - Algorithms that employ algorithms use themselves to solve single or multiple identical problems. For example, every successive call that recursive algorithms make involves running a small version of itself.
- There should be a
or*terminating condition*to prevent recursions from running endlessly. And, there should be a*stopping case*that does not execute a recursive call.*base case* - Three critical components of a recursive algorithm design are
(identifying identical minor problems),*decomposition*(using answers of smaller problems to solve the primary problem), and*composition*(the smallest problem that can be solved without any further decomposition).*identifying the base/stopping case*

Recursion can seem challenging for Java beginners, and professional **Java assignment help** services offer astute guidance. The 5 programming examples below investigate the recursive problem-solving process in detail.

**5 Superb Java Programs On Recursion**

**Factorial Of A Number**

The factorial of a number is the product of all the numbers preceding it. Programs on factorials are one of the most common coding problems for Java beginners. The basic algorithm for finding the factorial of any number ** n **(

*n*

*e*

*N**; where N denotes all natural numbers)*is as follows:

*START**Declare integer variables***n**and**ans***Read***n***Declare a public static function***Factorial**that executes the recursive logic=*Ans*(n)*Factorial*

*public static int Factorial (int n)*

*{*

* Declare an integer fact*

*If ( n *>1)// decomposition

** fact** = Factorial (

**-1) ***

*n***// the function composes the necessary solution by calling itself**

*n**else*

*fact** = 1 //* base case

*return ***fact**

**}**

*Print***Ans**

Every recursive call that ** Factorial** makes involves the execution of a smaller version of itself. However, the base case does not execute a recursive call & stops the recursion.

Here is an improved version of the recursive factorial function in Java code.

*Public static int factorial (int n)*

*{*

*If (n==1)*

*return 1;*

*else *

*return factorial (n-1) * n;*

*}*

**Sorting a Stack using Recursion**

Stacks are contiguous blocks of memory spaces for storing data. Extracting data from a stack requires one to follow the ** LIFO **(

**) rule; the last element to be entered in the stack is the first one to go out.**

*Last In First Out*Recursion can sort a stack and be a much more efficient way without consuming excessive resources. Programming problems that ask to sort a stack using recursion typically impose certain restrictions on the coder. In our case, we use only the following abstract data type functions on a stack *S*:

** is_empty(S)**: Checks whether the stack is empty or not

*push(S)**: *Pushes an element into the stack

** pop(S)**: Pops an element out of the stack

*top(S)**: *Returns the value from the top of the stack, that is, the last item that enters the stack

Here’s the stack that needs to be sorted through recursion:

-3 ß Top of the Stack and the last element entered

14

18

-5

30

We want to sort the stack in descending order:

30

18

14

-3

-5

One of the simplest ways to sort a stack is to empty it first, sort the elements, and then insert each element one by one, starting with the lowest one first.

The ** pop(S) **method is used to eject all elements. Then, we create two methods,

**and**

*sortStack(S)*

*sortInsert(S, temp)*Here’s the primary method à

*sortStack(stack S)*

* *

* if stack is not empty:*

* temp = pop(S);*

* sortStack(S);*

* sortInsert(S, temp)*

* *

The sorting and insertion code is as follows à

*sortInsert(Stack S, element)*

* if stack is empty or element > top element*

* pish (S, elem)*

* else*

* temp = pop(S)*

* sortInsert(S, element)*

* push(S, temp)*

* *

**The Recaman’s Sequence**

Recaman’s sequence is a famous numerical sequence in mathematics and computer science. Elements in this sequence have a recurrence relationship with one another.

The following conditions/constraints define the Recaman’s Sequence:

**A _{n} = 0, if n=0**

** A _{n-1} – n**

** A _{n-1} + n, if A_{n-1} – n < 0 and the value is already in the sequence**

The basic algorithm for developing the sequence is

*A[0]=0 // A is an array*

*If n > 0 and the number is not yet in the sequence*

* A[n]= A[n-1] – n*

*Else*

* A[n]=A[n-1] + n*

Below is a simple code in Java where all elements are stored in an array:

*Import **java.io.*;*

*Class **RecSeq {*

*static void **recaman( int n)*

*{*

* int arr[] = int new[n]; // creating a new array *

* arr[0]=0;*

* System.out.print(arr[0]+” , “);*

* for (int I = 1; I < n; i++)*

* {*

* int curr = arr[i-1] – n;*

* int j=0;*

* for (j=0; j < I; j++)*

* { *

* if(arr[j] == cur || curr < 0)*

* {*

* curr = arr[i-1] + I;*

* break;*

* }*

* }*

* arr[i]= curr;*

* System.out.print(arr[i]+” , “);*

*}*

*}*

* *

*public static void **main (String[] args)*

*{*

* int n=20;*

* recaman(n);*

*}*

*} *

**A Palindrome Number**

Palindrome numbers read the same from both the front and the back. Therefore, the critical aspect of checking whether a number is a palindrome is to reverse it and match it with the original.

Here’s the Java code for checking Palindrome numbers.

*Import **java.io.*;*

*class **pal*

*{*

*static int **rev( int n, int temp)*

*{*

* If(n==0)*

*return **temp;*

*temp = (temp * 10) + (n % 10); // We deal with decimals so modulus divisions with 10 extract each digit from the unit’s side. Temp is storing the test number in reverse.*

**return **rev(n/10, temp); // *Dividing any number by 10 in sequence removes a digit one by one*

*}*

*public static void **main(String[] args)*

*{*

*int **n = 12321;*

*int **temp= rev(n,0);*

*if **(temp == n)*

* System.out.println(“YES”);*

*else*

* **System.out.println(“NO”);*

*}*

*}*

**The Sum Triangle Of An Array**

In this program, the base of a right-angled triangle is the input array. The subsequent layers above are the sum of adjacent elements, and the summation goes on until a single value is achieved. That single value is the vertex of the triangle.

- Recursion is a vital aspect of this problem. In every instance, we build a new array that contains the sums of consecutive elements of the array passed as the parameter.
- The newly created arrays are the parameters of each recursive call.
- Finally, all arrays are printed so that the smaller ones are printed first.

Here’s the solution for an array [5, 12,2,25,64]

229

72,157

31,41,116

17, 14, 27, 89

5, 12, 2, 25, 64

And, here’s the Java code.

*import **java.util.*;*

*import** java.lang.*;*

*public class** ConstructTriangle*

*{*

* public static void** printTriangle(int[] A)*

* {*

* if (A.length < 1)*

* return**;*

* int[] temp = new int[A.length – 1];*

* for** ( int i = 0; i < A.length – 1; i++)*

* {*

* int** x = A[i] + A[i + 1];*

* temp[i] = x;*

* }*

* printTriangle(temp);*

* System.out.println(Arrays.toString(A));*

* }*

* public static void** main(String[] args)*

* {*

* int[] A = { 1, 2, 3, 4, 5 };*

* printTriangle(A);*

* }*

*}*

Well, those were five extraordinary recursive programming problems in Java. The above 5 programs are just a few from a wide range of problems on recursion. Read more and practice more to boost your concepts on this powerful problem-solving method and master Java programming.

And, avail of quality Java assignment help from a reputed academic service if you find classroom teaching inadequate!

All the best!