JAVA Programming to use
Recursion for problem solving
- Write a java program to find minimum and maximum number from an array using recursion.
a. Ask user for the size of
the array. (Ex. 10)
b. Create an array with the
size entered by user (Ex. a[10]).
c. Ask user to enter array
elements and store it in array (Ex. user will enter 10 integers which will be
stored in the array).
d. Write a recursive method
that returns the smallest integer from this array.
e. Write a recursive method
that returns the largest integer from this array.
CODE
:
import java.util.Arrays;
import java.util.Scanner;
public class Recursion {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
int [] myArray = new int[length];
System.out.println("Enter the elements of the array:");
for(int i=0; i<length; i++ ) {
myArray[i] = s.nextInt();
}
System.out.println("\n Array : "+Arrays.toString(myArray));
System.out.println("\n The smallest integer of array : " + findMinRec(myArray, length));
System.out.println("\n The largest integer of array : "+findMaxRec(myArray, length));
}
public static int findMinRec(int myArray[], int length) {
if(length == 1)
return myArray[0];
return Math.min(myArray[length-1], findMinRec(myArray, length-1));
}
public static int findMaxRec(int myArray[], int length) {
if(length == 1)
return myArray[0];
return Math.max(myArray[length-1], findMaxRec(myArray, length-1));
}
}
OUTPUT :
No comments:
Post a Comment