Codemonkey's hacks
- Hack: Create method that sets all elements in array to n
- Hack: Find the average number of a diagonal in a 2d array
void setArray(int[] arr, int n) {
// your code here
for (int i = 0; i < arr.length; i++) // for loop to iterate through the array
{
arr[i] = n; // set the value of the array at index i to n
}
}
int[] array = new int[10];
setArray(array, 10); // set all values in array to 10
for (int i = 0; i<array.length; i++) {
System.out.println(array[i]); // print out all values in array
}
// Should print all 10s when working properly
//Example finding the max in an array.
//Finds the maximum in an array
public static int average(int[] array) {
// put your code here
int sum = 0; //sum of all elements
int avg = 0; //average of all elements
for (int n: array){
sum += n; //add each element to the sum
}
avg = sum / array.length; //divide the sum by the number of elements
return avg; //return the average
}
//tester array
int[] test = {3, 5, 7, 2, 10}; //average should be 5.4
//returns 10
System.out.println(average(test)); //prints 5
public static int averageDiagonal (int[][] array2D) {
// your code here
int sum = 0; // sum of all elements
for (int r = 0; r < array2D.length; r++){
for (int c = 0; c < array2D[r].length; c++){
if (r == c){
sum += array2D[r][c]; //add each element to the sum
}
}
}
return sum / array2D.length; //return the average
}
int[][] arr = {
{1,2,3,4,5,6},
{7,8,9,10,11,12},
{0,1,2,3,4,5},
{10,11,12,13,14,15},
{15,16,17,18,19,20}
};
System.out.println(averageDiagonal(arr));