Computer Science 2 Lab Exercises – 2D Arrays

You can use the below code as a starter. Use a separate copy for each exercise! It will fill a “square” array of size ARR_SIZE with random values from 1 to MAX_VALUE or you can fill the array with hard coded values of your choice or you can fill it any other way of your choosing.

public class Arrays2D

{

static final int ARR_SIZE = 10;

static final int MAX_VALUE = 1000;

public static void main(String[] args)

{

int[][] arr2D = new int[ARR_SIZE][ARR_SIZE];

for (int row=0; row<arr2D.length; row++) //loop fills the array

{

for (int col=0; col<arr2D[row].length; col++)

{

arr2D[row][col] = (int)(Math.random()*MAX_VALUE+1);

}

}

// ADD ALL OF YOUR INCREDIBLE AMAZING CODE HERE

printArr(arr2D); // calls printArr method to print the “after”

}//end main

public static void printArr(int[][] arrToPrint) //method prints array

{

for (int r=0; r<arrToPrint.length; r++)

{

for (int c=0; c<arrToPrint[r].length; c++)

{

if (arrToPrint[r][c] < 10)

System.out.print(" ");

if (arrToPrint[r][c] < 100)

System.out.print(" ");

System.out.print(arrToPrint[r][c]+" ");

} // end of row

System.out.println(); //change lines

}

}

} // end class

Exercise 0 --- Sum and Average

Add code to your main method to calculate and print the sum of all the array elements and the average of all the elements. For extra fun print the sum of each row and column individually.

Exercise 1 --- Major Diagonal

Write a program that asks the user for a number and inserts that number on the main diagonal (top left to bottom right). The rest of the 2D array is unchanged.You should print both the before and after.

Exercise 2 --- Minor Diagonal

Write a program that asks the user for a number and inserts that number on the minor diagonal (bottom left to top right). The rest of the 2D array is unchanged.You should print both the before and after.

Exercise 3 --- Transpose

Write a program that transposes the 2D array (switches rows and columns).You should print both the before and after.

Hint: this exercise is very similar to the exercise where we reversed the order of elements in an array.