In: Computer Science
Please show screenshot outputs and fully functional code for the Java program.
Write the following methods to
1) read the content of an array of 5 doubles
public static double[] readingArray()
2) find and print:the smallest element in an array of 5 double
public static void smallest(double [] array)
3) find and print:the largest element in an array of 5 doubles
pubic static void largest (double [] array)
In the main method
- invoke readingArray and enter the following numbers 50 20 10 40 30
- invoke smallest
- invoke largest.
Java code:
import java.util.*;
public class Abc
{ //This function will read the Array
public static double[] readingArray()
{
Scanner sc = new Scanner(System.in);
double array[] = new double[5];
System.out.print("Please enter array elements: ");
for(int i=0;i<5;i++){
array[i] = sc.nextDouble();
}
return array;
}
//This function will take array and display smallest element.
public static void smallest(double [] array){
//Initialize min with first element of array.
double min = array[0];
for (int i = 0; i < array.length; i++) {
//Compare elements of array with min
if(array[i] < min){
min = array[i];
}
}
System.out.println("Smallest element in given array is: " + min);
}
//This function will take array and display largest element.
public static void largest (double [] array){
//Initialize max with first element of array.
double max = array[0];
for (int i = 0; i < array.length; i++) {
//Compare elements of array with max
if(array[i] > max){
max = array[i];
}
}
System.out.println("Largest element in given array is: " + max);
}
// main() method
public static void main(String[] args)
{
// initializing double array
double[] array;
array = readingArray(); //called readingArray method
smallest(array); //Calling the smallest method with 1 parameter.
largest(array); //Calling the largest method with 1 parameter.
}
}
OUTPUT: