Problem:
Compute the average of the given array values in JAVA
Algorithm:
1. Initialize the array with random values.
2. Declare a variable called sum and initialize the value with 0.
3. Iterate the array and calculate the sum.
4. Divide the sum with the array length
4. Print out the array and average value of the array
Solution:
import java.util.*;
import java.security.SecureRandom;
class FindAverageOfArrayUtility{
public static void main(String[] args){
int[] a= new int[3];
initializeArray(a);
printArray(a);
System.out.println("Average of given array values is : " + findAverageValue(a));
}
public static void initializeArray(int[] array){
Random random = new SecureRandom();
for(int i=0;i < array.length; i++){
array[i] = random.nextInt(100);
}
}
public static void printArray(int[] array){
Arrays.stream(array).forEach(System.out::println);
}
public static double findAverageValue(int[] array){
int sum = 0;
for(int i=0; i < array.length; i++){
sum = sum + array[i];
}
return sum/array.length;
}
}
Output:
24
80
45
Average of given array values is : 49.0
38
75
89
Average of given array values is : 67.0
Compute the average of the given array values in JAVA
Algorithm:
1. Initialize the array with random values.
2. Declare a variable called sum and initialize the value with 0.
3. Iterate the array and calculate the sum.
4. Divide the sum with the array length
4. Print out the array and average value of the array
Solution:
import java.util.*;
import java.security.SecureRandom;
class FindAverageOfArrayUtility{
public static void main(String[] args){
int[] a= new int[3];
initializeArray(a);
printArray(a);
System.out.println("Average of given array values is : " + findAverageValue(a));
}
public static void initializeArray(int[] array){
Random random = new SecureRandom();
for(int i=0;i < array.length; i++){
array[i] = random.nextInt(100);
}
}
public static void printArray(int[] array){
Arrays.stream(array).forEach(System.out::println);
}
public static double findAverageValue(int[] array){
int sum = 0;
for(int i=0; i < array.length; i++){
sum = sum + array[i];
}
return sum/array.length;
}
}
Output:
24
80
45
Average of given array values is : 49.0
38
75
89
Average of given array values is : 67.0
No comments:
Post a Comment