In: Computer Science
java by using Scite
Objectives:
1. Create one-dimensional arrays and two-dimensional arrays to solve problems
2. Pass arrays to method and return an array from a method
Problem 1:
Find the average of an array of numbers (filename: FindAverage.java)
Write two overloaded methods with the following headers to find the average of an array of integer values and an array of double values:
public static double average(int[] num)
public static double average(double[] num)
In the main method, first create an array of integer values with the array size of 5 and invoke the first method to get and display the average of the first array, and then create an array of double values with the array size of 6 and invoke the second method to get and display the average of the second array.
You can generate the array values using the Math.random() method with the range from 0 to 9. Keep two decimals for the average values.
Hello and Hope you're having a good day. The following code was created using Java and should definitely serve your purpose.
Program:
import java.util.*;
public class FindAverage{
//static method finds int average
public static double average(int[] num){
double y = 0;
for(int
i=0;i<num.length;i++){
y+=num[i];
}
y /= num.length;
return y;
}
//static method finds double average
public static double average(double[]
num){
double y = 0;
for(int
i=0;i<num.length;i++){
y+=num[i];
}
y /= num.length;
return y;
}
public static void main(String []args){
//int block
//creation
int[] num = new
int[5];
for(int
i=0;i<5;i++){
num[i] = (int) ((Math.random() * (10 - 0)));
}
//display array
System.out.println("Int
Array:");
for(int
i=0;i<5;i++){
System.out.println(num[i]);
}
//find and print
average
double s =
average(num);
System.out.println("Average of Int Array is "+s);
//double block
//creation
double[] num2 = new
double[6];
for(int
i=0;i<6;i++){
num2[i] = Math.random() * (10 - 0);
}
//display array
System.out.println("Double Array:");
for(int
i=0;i<6;i++){
System.out.println(num2[i]);
}
//find and print
average
double s2 =
average(num2);
System.out.println("Average of Double Array is "+s2);
}
}
NB: There are better methods to generate Random numbers in Java like the Random Package in Utils. Math.Random returns a double which has to be bound and typecasted to an int to suit our needs. Please look into those for more information.
I hope this has helped you. Thank you and have a nice day. Happy learning!