In: Computer Science
show some example of few recursive problem in java language and the solution code. Need more practice as a new learner
Find the factorial of Code :
public class FactRec {
private static int fact(int n) {
// base case when we reached 0 return 1
if (n == 0)
return 1;
else
// multiply n with its previous number
return (n * fact(n - 1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is "+fact(5));
}
}
Prints the array elements using recursion
public class ArrayRec {
public static void main(String[] args) {
int arr[]= {1,2,3,4,5};
print(arr,0);
}
private static void print(int[] arr, int i) {
// base case when we reached the array length than stop
if(i==arr.length)
return;
//print element
System.out.print(arr[i]+" ");
// move too next element
print(arr,i+1);
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
Please Like and Support me as it helps me a lot