Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Matrices {
  4.  
  5. public static void main(String[] args) {
  6. Scanner scanner = new Scanner(System.in);
  7. System.out.print("Enter number of rows: ");
  8. int rows = scanner.nextInt();
  9. System.out.print("Enter number of columns: ");
  10. int columns = scanner.nextInt();
  11. System.out.println();
  12. System.out.println("Enter first matrix");
  13. int[][] a = readMatrix(rows, columns);
  14. System.out.println();
  15. System.out.println("Enter second matrix");
  16. int[][] b = readMatrix(rows, columns);
  17. int[][] sum = add(a, b);
  18. int[][] difference1 = subtract(a, b);
  19. int[][] difference2 = subtract(b, a);
  20. System.out.println();
  21. System.out.println("A + B =");
  22. printMatrix(sum);
  23. System.out.println();
  24. System.out.println("A - B =");
  25. printMatrix(difference1);
  26. System.out.println();
  27. System.out.println("B - A =");
  28. printMatrix(difference2);
  29. }
  30.  
  31. public static int[][] readMatrix(int rows, int columns) {
  32. int[][] result = new int[rows][columns];
  33. Scanner s = new Scanner(System.in);
  34. for (int i = 0; i < rows; i++) {
  35. for (int j = 0; j < columns; j++) {
  36. result[i][j] = s.nextInt();
  37. }
  38. }
  39. return result;
  40. }
  41.  
  42. public static int[][] add(int[][] a, int[][] b) {
  43. int rows = a.length;
  44. int columns = a[0].length;
  45. int[][] result = new int[rows][columns];
  46. for (int i = 0; i < rows; i++) {
  47. for (int j = 0; j < columns; j++) {
  48. result[i][j] = a[i][j] + b[i][j];
  49. }
  50. }
  51. return result;
  52. }
  53.  
  54. public static int[][] subtract(int[][] a, int[][] b) {
  55. int rows = a.length;
  56. int columns = a[0].length;
  57. int[][] result = new int[rows][columns];
  58. for (int i = 0; i < rows; i++) {
  59. for (int j = 0; j < columns; j++) {
  60. result[i][j] = a[i][j] - b[i][j];
  61. }
  62. }
  63. return result;
  64. }
  65.  
  66. public static void printMatrix(int[][] matrix) {
  67. int rows = matrix.length;
  68. int columns = matrix[0].length;
  69. for (int i = 0; i < rows; i++) {
  70. for (int j = 0; j < columns; j++) {
  71. System.out.print(matrix[i][j] + " ");
  72. }
  73. System.out.println();
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement