Java 程序用于相加两个矩阵

编写一个带有示例的矩阵相加程序。或者编写一个 Java 程序,使用 for 循环相加两个多维数组,并以矩阵格式打印它们。

A = [ a11  a12 a21  a22 ]

B = [ b11  b12 b21  b22 ]

A + B = [a11 + b11  a12 + b12 a21 + b21  a22 + b22 ]

Java 程序使用 for 循环相加两个矩阵

在此 Java 示例中,我们声明了两个具有随机值的整数矩阵。接下来,我们使用 For 循环迭代并将 X 的每一行和列值加到 Y 矩阵中。稍后,我们使用另一个 for 循环来打印最终输出。

public class addTwoMatrix {

	public static void main(String[] args) {
		int[][] x = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}};
		int[][] y = {{ 5, 15, 25}, {35, 45, 55}, {65, 75, 85}};
		
		int[][] sum = new int[3][3];
		int i, j;
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				sum[i][j] = x[i][j] + y[i][j];
			}
		}
		System.out.println("------ The addition of two Matrices ------");
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				System.out.format("%d \t", sum[i][j]);
			}
			System.out.println("");
		}
	}
}
Program to add two Matrices using for loop

相加两个矩阵 示例 2

Java 示例与上述相同。但是,此 Java 代码允许用户输入行数和列数,然后要求输入项。请参考 C 语言矩阵相加程序文章以了解迭代式程序执行。

import java.util.Scanner;

public class Example {
	private static Scanner sc;
	public static void main(String[] args) {
		int i, j, rows, columns;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Please Enter Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr1 = new int[rows][columns];
		int[][] arr2 = new int[rows][columns];
		
		System.out.println("\n Please Enter the First Mat Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr1[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n Please Enter the Second Mat Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr2[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n-----The Sum of two Matrixes----- ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				System.out.format("%d \t", (arr1[i][j] + arr2[i][j]));
			}
			System.out.println("");
		}
	}
}
Add two Matrices using For loop