In this task, you are being asked to write methods that manipulate arrays in Java.
1. Write a method called swapFirstAndLastRow which will take a two-dimensional
integer array as argument and swap all the values of first row and last row with each
other.
You may use the following header for this method:
static void swapFirstAndLastRow(int[][] array)
For example, if we pass the following two-dimensional array to this method:
5 7 9 4 3 1
2 4 9 7 6 5
3 6 8 7 9 4
1 9 7 5 6 3
Then the array will become:
1 9 7 5 6 3
2 4 9 7 6 5
3 6 8 7 9 4
5 7 9 4 3 1
2. Write a third method called printArray which will take a two-dimensional integer
array as argument and prints all elements of array. The method should print each row line
by line.
You may use the following header for this method:
static void printArray (int[][] array)
Take two numbers from the user as the size of rows and columns of the array and call the
methods in the following order:
printArray()
swapFirstAndLastRow()
printArray
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
int[][] array = { { 5, 7, 9, 4, 3, 1 }, { 2, 4, 9, 7, 6, 5 }, { 3, 6, 8, 7, 9, 4 }, { 1, 9, 7, 5, 6, 3 } };
printArray(array);
swapFirstAndLastRow(array);
System.out.println();
printArray(array);
}
static void swapFirstAndLastRow(int[][] array) {
int[] arrayTemp = array[0];
array[0] = array[array.length - 1];
array[array.length - 1] = arrayTemp;
}
static void printArray(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
Comments
Leave a comment