Final answer:
The Transpose program demonstrates the effective creation and manipulation of matrices, offering a practical implementation of matrix transposition in Java for educational and practical purposes.
Step-by-step explanation:
The program begins by prompting the user to input the number of rows and columns for a rectangular matrix. It then calls the 'matrixSetup' method to generate and populate the matrix with random integers. The original matrix is printed, followed by a call to the 'transpose' method, which calculates and returns the transpose of the matrix. The transpose matrix is then printed. The 'matrixSetup' method initializes a matrix with random integers from 0 to 99. The 'transpose' method swaps the rows and columns of the given matrix to obtain the transpose. This program provides a simple and interactive way to understand matrix transposition in Java.
import java.util.Random;
import java.util.Scanner;
public class Transpose {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Ask the user to provide the number of rows and columns
System.out.print("Enter the number of rows (2 to 10): ");
int n = scanner.nextInt();
System.out.print("Enter the number of columns (2 to 10): ");
int m = scanner.nextInt();
// Step 2: Call Matrix Setup method to create and populate the matrix
int[][] matrix = matrixSetup(n, m);
// Step 3: Print the original matrix
System.out.println("Original Matrix:");
printMatrix(matrix);
// Step 4: Call Transpose method to get the transpose of the matrix
int[][] transposeMatrix = transpose(matrix);
// Step 5: Print the transpose matrix
System.out.println("Transpose Matrix:");
printMatrix(transposeMatrix);
scanner.close();
}
// Method to create and populate a matrix with random integers
private static int[][] matrixSetup(int rows, int cols) {
int[][] matrix = new int[rows][cols];
Random random = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = random.nextInt(100);
}
}
return matrix;
}
// Method to print a matrix
private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
// Method to calculate and return the transpose of a matrix
private static int[][] transpose(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int[][] transposeMatrix = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposeMatrix[j][i] = matrix[i][j];
}
}
return transposeMatrix;
}
}