(22) Write a recursive method that returns the
smallest integer in an array. Write a test program that prompts the user
to enter an integer and display its product.
Program Code-1: Write a recursive method that returns the smallest integer in an array.
public class OOP_22
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter five integers: ");
int[] list = new int[5];
for (int i = 0; i < list.length; i++)
{
list[i] = input.nextInt();
}
System.out.println("The smallest element is " + min(list));
}
public static int min(int[] list)
{
int min = list[list.length - 1];
int index = list.length - 1;
return min(list, index, min);
}
private static int min(int[] list, int index, int min)
{
if (index < 0)
{
return min;
}
else if (list[index] < min)
{
return min(list, index - 1, list[index]);
}
else
{
return min(list, index - 1, min);
}
}
}
Output-1:
Program Code-2:Write a test program that prompts the user to enter an integer and display its product.
import java.util.Scanner;
public class OOP_22_2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int product=1;
System.out.print("Enter five integers: ");
int[] list = new int[5];
for (int i = 0; i < list.length; i++)
{
list[i] = input.nextInt();
product *= list[i];
}
System.out.println("The Product of elements is " + product);
}
}
Output-2:
No comments:
Post a Comment