MacroMonkey Lesson
Lesson
- Hack: Create method that sets all elements in array to n
- Hack: Write an array to find the average of an array
- 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++)
{
arr[i] = n;
}
}
int[] array = new int[10];
setArray(array, 10);
for (int i = 0; i<array.length; i++) {
System.out.print(array[i]);
if(i != 9){
System.out.print(",");
}
}
public static int average(int[] array) {
// put your code here
int sum = 0;
int avg = 0;
for (int n: array){
sum += n;
}
avg = sum / array.length;
return avg;
}
//tester array
int[] test = {3, 5, 7, 2, 10};
//returns 10
System.out.println("Average of array = " + average(test));
public static int averageDiagonal (int[][] array2D) {
// your code here
int sum = 0;
for (int r = 0; r < array2D.length; r++){
for (int c = 0; c < array2D[r].length; c++){
if (r == c){
sum += array2D[r][c];
}
}
}
return sum / array2D.length;
}
int[][] arr = {
{1,2,3,4,5,6},
{7,8,9,10,11,12},
{13,14,15,16,17,18},
{19,20,21,22,23,24},
{25,26,27,28,29,30}
};
System.out.println("Average of diagonal = "+averageDiagonal(arr));