Lab 2 Hacks
//BASIC ARRAY CONCEPTS
//Declare an array and then allocate memory
int myArray[];
myArray = new int[4];
//Declare while directly assign values
int[] myArray1 = new int[]{ 1, 6, 7, 9};
//Initialize element
myArray[0] = 2;
//Create an array of objects
Object[] arr = new Object[5];
//Basic for loop to print elements of array
int[] arr1 = {0, 6, 8, 2};
// Looping through array by incrementing value of i
//'i' is an index of array 'arr1'
for (int i = 0; i < arr1.length; i++) {
// Print array element present at index i
System.out.println(i + " " + arr1[i]);
}
// NOTE: You may also use an enhanced for loop
for(int value: arr1){
System.out.println(value);
}
void setArray(int[] arr, int n) {
for (int i = 0; i<array.length; i++) {
arr[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
//Example finding the max in an array.
//Finds the maximum in an array
public static float average(int[] array) {
float sum = 0;
for (int element : array) {
sum += element;
}
return sum/array.length;
}
//tester array
int[] test = {3, 5, 7, 2, 10};
//returns 10
System.out.println(average(test));
public static float averageDiagonal (int[][] array2D) {
int sum = 0;
int count = 0;
for (int i = 0; i < array2D.length; i++) {
try {
sum += array2D[i][i];
count++;
} catch(Exception e) {
}
}
return (float) sum/count;
}
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));