In: Computer Science
Create an application containing an array that stores 5 integers. The application should call five methods from Array2 class that in turn (1) display all the integers, (2) display all the integers in reverse order, (3) display the sum of the integers, (4) display all values less than a limiting argument, and (5) display all values that are higher than the calculated average value. Save the file as ArrayTest.java.
In the below code , two classes are declared : Array2 and ArrayTest
5 methods are defined in Array2 class:
display(): to display all array elements, For loop used for it
Reverse(): display elements in reverse order , one more array is used, reversed elements are stored in it and displaed. For loop used for it
SumOfArray(): added all the elements of array and displayed in console
lessLimitingArgument(): one limit element is passed as argument, all the elements less than that element in array are displayed in console
highAverageElement(): average of elements of array is found and elements greater than average are displayed in console
In ArrayTest class:
Elements of array are inputted from console
object of Array2 class in declared and all the function of Array2 class are called
________________________________________
Please find the code in Java:
import java.util.*;
class Array2{
void display(int[] arr){
System.out.println("List of elements in array are: ");
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
void reverse(int[] arr){
System.out.println("Reversed array elements are: ");
int[] reverseArr=new int[arr.length];
int j=0;
for(int i=arr.length-1;i>=0;i--){
reverseArr[i]=arr[j];
j++;
}
for(int i=0;i<reverseArr.length;i++){
System.out.println(reverseArr[i]);
}
}
void sumOfArray(int[] arr){
int sum=0;
for(int i=0;i<arr.length;i++){
sum+= arr[i];
}
System.out.println("Sum of elements of array is: "+sum);
}
void lessLimitingElement(int[] arr,int limit){
System.out.println("Elements less than limiting argument are:
");
for(int i=0;i<arr.length;i++){
if(limit>arr[i]){
System.out.println(arr[i]);
}
}
}
void highAverageElement(int[] arr){
int avg=0,sum=0;
for(int i=0;i<arr.length;i++){
sum+= arr[i];
}
avg=sum/arr.length;
System.out.println("Elements higher than average are: ");
for(int i=0;i<arr.length;i++){
if(avg<arr[i]){
System.out.println(arr[i]);
}
}
}
}
public class ArrayTest
{
public static void main(String[] args) {
Scanner scr=new Scanner(System.in);
int[] arr=new int[5];
System.out.println("Enter 5
Elements in array:");
for(int
i=0;i<arr.length;i++){
arr[i]=scr.nextInt();
}
System.out.println("Enter limiting element : ");
int limit=scr.nextInt();
Array2 obj=new Array2();
obj.display(arr);
obj.reverse(arr);
obj.sumOfArray(arr);
obj.lessLimitingElement(arr,limit);
obj.highAverageElement(arr);
}
}
Please find the OUTPUT screenshot: