在这个Java程序中,我们将讨论添加两个矩阵。为此,我们必须读取两个矩阵A和B的元素,然后将A和B的总和计算到结果矩阵sum中。
多维数组称为矩阵。声明二维数组的语法如下所示。
Data_type[1st dimension][2nd Dimension]array_name=new Data_type[Size1][Size2];
一个示例如下所示
int[][] A=new[10][10];
这里创建的矩阵A的大小为10 X 10。
首先,我们必须声明类AddMatrix。然后打开主函数。创建一个扫描器类的对象,如in。将行数和列数读入变量m和n。然后初始化三个大小为m和n的矩阵。然后使用for循环读取矩阵A的元素。然后读取矩阵B的元素。之后使用嵌套for循环计算和矩阵为sum[i][j]=A[i][j]+B[i][j]。然后显示矩阵sum的每个元素作为和矩阵。
步骤1:声明带有public修饰符的类AddMatrix。
步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始
步骤3:声明整数变量m,n,i,j。
步骤4:将矩阵的行数和列数读入变量m和n。
步骤5:将矩阵A[][]、B[][]和sum[][]初始化为整数。
步骤6:使用for循环将A的元素读入A[i][j]。
步骤7:使用for循环将B的元素读入B[i][j]。
步骤8:使用嵌套for循环计算和为sum[i][j]=A[i][j]+B[i][j]。
步骤9:使用嵌套for循环显示和为sum[i][j]。
import java.util.Scanner;
public class AddMatrix {
public static void main(String args[])
{
int m, n, i, j;
Scanner in = new Scanner(System.in);
System.out.println("Input number of rows of matrix: ");
m = in.nextInt();
System.out.println("Input number of columns of matrix: ");
n = in.nextInt();
int A[][] = new int[m][n];
int B[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Input elements of first matrix: ");
for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
A[i][j] = in.nextInt();
System.out.println("Input the elements of second matrix: ");
for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
B[i][j] = in.nextInt();
for ( i = 0 ; i < m ; i++ )
for ( j = 0 ; j < n ; j++ )
sum[i][j] = A[i][j] + B[i][j];
System.out.println("Sum of the matrices:-");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
System.out.print(sum[i][j]+"\t");
System.out.println();
}
}
}
Input number of rows of matrix: 2 Input number of columns of matrix: 2 Input elements of first matrix: 1 2 3 4 Input the elements of second matrix: 5 6 7 8 Sum of the matrices:- 6 8 10 12