Lab 2 Hacks
//Hack #1: Create method that sets all elements in array to n
void setArray(int[] arr, int n) {
for (int i = 0; i < arr.length; i++) {
arr[i] = n;
//sets each of the 0 to n, which is 10 in this case
}
}
int[] array = new int[10];
setArray(array, 10);
for (int i = 0; i<array.length; i++) {
System.out.println(array[i]);
}
// Should print all 10s when working properly
10
//Hack #2: Write an array to find the average of an array
//Example finding the max in an array.
//Finds the maximum in an array
public static int average(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
} //adds each array element to sum and divides by length of array
return sum / array.length;
}
//tester array
int[] test = {3, 5, 7, 2, 10};
//returns 10
System.out.println(average(test));
public static void main(String[] args){
int[][] arrayOne = new int[5][7];
for (int row = 0; row < arrayOne.length; row++){
for (int col = 0; col < arrayOne[row].length; col++){
arrayOne[row][col] = row+col - 1;
}
}
System.out.println(arrayOne[4][6]);
}
//Hack 3 - print average of diagonal
public static double averageDiagonal (int[][] array2D) {
// your code here
int sum = 0;
int count = 0;
int row = 0;
int col = 0;
// Iterate over the diagonal elements of the array
while (row < array2D.length && col < array2D[0].length) {
sum += array2D[row][col];
count++;
row++;
col++;
}
// Calculate and return the average as double
return (double) sum / count;
}
int[][] arr = {
{1,2,3,4},
{5,6,7,8},
{9,1,2,3}
//populating an arr
};
System.out.println(averageDiagonal(arr));