Recursion in Java
In this tutorial we will see how to do recursion in java, and also see examples of recursion using java.
A recursive method in Java is a method that calls itself, and this process is known as recursion. Recursion in java provides a way to break complicated problems down into simple problems which are easier to solve.
Recursion although a tricky concept is very important topic for java programmers. Online Java Tutor can guide through personalized java training and help students understand basics and advance java coding.
Factorial of a Number Using Recursion in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Factorial { public static int factorial(int n) { if (n != 0) // ending condition return n * factorial(n - 1); // recursive call else return 1; } public static void main(String[] args) { int num=7; int fact=factorial(num); System.out.println("Factorial of the number "+num+" is "+fact); } } |
Output -> Factorial of the number 7 is 5040
Fibonacci Series using Java Recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Fibanoccai { public static int fibonacci(int x) { if (x == 0) { return 0; } if (x == 1 || x == 2) { return 1; } return fibonacci(x - 2) + fibonacci(x - 1); } public static void main(String[] args) { int maxNumber = 10; System.out.print("Fibonacci Series of " + maxNumber + " numbers: "); for (int i = 0; i < maxNumber; i++) { System.out.print(fibonacci(i) + " "); } } } |
Output -> Fibonacci Series of 10 numbers: 0 1 1 2 3 5 8 13 21 34
Using Java Recursion to Reverse a given String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class StringReverse { //recursive method to reverse a given string void reverseString(String str) { //base condition if ((str==null)||(str.length() <= 1)) System.out.println(str); else { System.out.print(str.charAt(str.length()-1)); reverseString(str.substring(0,str.length()-1)); } } } public class Main{ public static void main(String[] args) { String input = "JavaTutorOnline"; System.out.println("The given string: " + input); StringReverse obj = new StringReverse(); System.out.print("The reversed string: "); obj.reverseString(input); } } |
Output
The given string: JavaTutorOnline
The reversed string: enilnOrotuTavaJ
Check if a given string is a Palindrome using Java Recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class Palindrome { public static boolean checkPalindrome(String s) { if (s.length() == 0 || s.length() == 1) { return true; } if (s.charAt(0) == s.charAt(s.length() - 1)) { return checkPalindrome(s.substring(1, s.length() - 1)); } return false; } public static void main(String args[]) { String s1="MADAM"; boolean b1=checkPalindrome(s1); if(b1==true) System.out.println("The String \""+s1+"\" is a Palindrome"); else System.out.println("The String \""+s1+"\" is not a Palindrome"); } } |
Output -> The String “MADAM” is a Palindrome
Find minimum number in an int array using Java Recursion
1 2 3 4 5 6 7 8 |
// function to find minimum number public static int findMin(int[] numbers, int startIndex, int endIndex) { // if size = 0 means whole array // has been traversed if (startIndex == endIndex) return numbers[startIndex]; // stopping condition return Math.min(numbers[endIndex], findMin(numbers, startIndex, endIndex - 1)); } |
Find the number of odd numbers in an int array using Java Recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Function to find number of odd integers public static int countOddNumbers(int[] elements, int startIndex, int endIndex) { int count = 0; if (startIndex == endIndex)// stopping condition { if (elements[startIndex] % 2 == 0) { count = count + 0; } else count = count + 1; return count; } else { if (elements[endIndex] % 2 == 0) { count = count + 0; } else count = count + 1; int i = countOddNumbers(elements, startIndex, endIndex - 1) + count; return i; } } |
Find the largest even int in an int array using Recursion in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Function to find the largest even int public static int computeLargestEven(int[] elements, int startIndex, int endIndex) { int largest = 0; if (startIndex == endIndex) { if (elements[startIndex] % 2 == 0) { largest = elements[startIndex]; } return largest; } else { if (elements[endIndex] % 2 == 0) return Math.max(elements[endIndex], computeLargestEven(elements, startIndex, endIndex - 1)); else return Math.max(0, computeLargestEven(elements, startIndex, endIndex - 1)); } } |
Find the sum of numbers larger then a number in an int array using recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Function to find the sum of numbers larger than the first public static int sumOfNumbersLargerThanFirst(int[] elements, int startIndex, int endIndex, int firstNumber) { int count = 0; if (startIndex == endIndex) { if (elements[startIndex] > firstNumber) { count = count + elements[startIndex]; } return count; } else { if (elements[endIndex] > firstNumber) { count = count + elements[endIndex]; } count = count + sumOfNumbersLargerThanFirst(elements, startIndex, endIndex - 1, firstNumber); return count; } } |
Main function to call the recursive methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Recursive { public static void main(String[] args) { int arr[] = new int[100]; InputStreamReader isr = new InputStreamReader(System.in); // System.in is a standard input stream object connected with the keyboard BufferedReader br = new BufferedReader(isr); String sr = null; int i = 0;// will keep track of how many int has been entered through the keyboard do { try { sr = br.readLine(); arr[i] = Integer.parseInt(sr); i++; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } while (!sr.equals("0")); // the array has been populated with values and i is storing number of inputs // calling function to find minimum number int min = findMin(arr, 0, i - 1); System.out.println("The minimum number is " + min); // calling function to find number of odd integers int o = countOddNumbers(arr, 0, i - 1); System.out.println("The count of odd integers in the sequence is " + o); // calling function to find the largest even int int lE = computeLargestEven(arr, 0, i - 1); System.out.println("The largest even integer in the sequence is " + lE); // calling function to find the sum of numbers larger than the first int sum = sumOfNumbersLargerThanFirst(arr, 0, i - 1, arr[0]); System.out.println("The sum of numbers larger than the first is " + sum); } } |
Leave a Reply