Week 4 Practice Problems (Sample Solutions)
[Topic: Arrays && Loops]
import java.util.Arrays;
// Problem 1 Test Case
int[] array = {7, 1, 4, 9, 18, 72, 36, 65};
squareUp(array);
System.out.println(Arrays.toString(array));
// [49, 1, 16, 81, 324, 5184, 1296, 4225]
// Problem 2 Test Case
System.out.println(average(array));
// Problem 2: 1397
public static void squareUp(int[] array) {
for(int i = 0; i < array.length; i++) {
array[i] = array[i] * array[i]; // (int) Math.pow(array[i], 2);
}
}
public static int average(int[] array) {
int sum = 0;
for(int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum / array.length;
}