Week of 4/17 -- Lesson 2
Arrays and 2D Arrays -- Hacks
- Hack # 1 -- Create method that sets all elements in array to n
- Hack # 2 -- Write an array to find the average of an array
- Hack #3 -- Find the average number of a diagonal in a 2d array
void setArray(int[] arr, int n) {
for (int i = 0; i < array.length; i++){
array[i] = n;
}
}
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
//Finds the average of an array
public static int average(int[] array) {
int sum = 0;
int total = 0;
for (int i = 0; i < array.length; i++){
sum += array[i];
total += 1;
}
int average = sum/total;
return average;
}
//tester array
int[] test = {3, 5, 7, 2, 10};
//returns 10
System.out.println(average(test));
public static int averageDiagonal (int[][] array2D) {
// your code here
int sum = 0;
int total = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (i == j) {
sum += arr[i][j];
total++;
}
}
}
int avg = sum/total;
return avg;
}
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));
public class Position {
private int row;
private int col;
public Position(int r, int c){
row = r;
col = c;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public static Position findPosition(int num, int[][] intArr){
for (int r = 0; r < intArr.length; r++){
for (int c = 0; c < intArr[0].length; c++){
if (intArr[r][c] == num) {
return new Position(r, c);
}
}
}
return null;
}
public static void main(String[] args) {
int[][] arr = {
{15,5,9,10},
{12,16,11,6},
{14,8,13,7}
};
Position pos = Position.findPosition(11, arr);
System.out.println("Row: " + pos.getRow() + ", Col: " + pos.getCol());
}
}
Position.main(null);