programa Java para restar dos matrices (la resta de dos matrices)

En este programa java, vamos a leer dos matrices y la búsqueda de su multiplicación en tercera matriz y la impresión de la matriz resultante.

Dadas dos matrices, tenemos que encontrar e imprimir su sustracción utilizando el programa Java.

Ejemplo

Input (Matrix 1)
55 66
99 88
Input (Matrix 2)
44 55
88 77
Output (Subtracted Matrix)
11 11
11 11

Programa para restar dos matrices en java

import java.util.Scanner;
public class MatrixSubtraction
{
public static void main(String args[])
{
int n,i,j;
//scanner class object
Scanner scan = new Scanner(System.in);
//input total number of rows and cols (i.e. base for both)
System.out.print("Enter the base of the matrices : ");
n = scan.nextInt();
//matrix (two_d array) object declarations
int mat1[][] = new int[n][n];
int mat2[][] = new int[n][n];
int mat3[][] = new int[n][n];
//input matrix 1
System.out.println("Enter the elements of the first matrix : ");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
mat1[i][j] = scan.nextInt();
}
}
//input matrix 2
System.out.println("Enter the elements of the second matrix : ");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
mat2[i][j] = scan.nextInt();
}
}
//subtracting matrices
System.out.println("Subtracting Matrices --Matrix1 - Matrix2--");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
mat3[i][j] = mat1[i][j] - mat2[i][j];
}
}
//printing final matrix
System.out.println("Result of Matrix1 - Matrix2 is : ");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.print(mat3[i][j]+ " ");
}
System.out.println();
}
}
}

salida 1

Enter the base of the matrices : 3
Enter the elements of the first matrix :
6 7 8
9 8 7
6 7 8
Enter the elements of the second matrix :
6 6 8
8 8 6
6 6 8
Subtracting Matrices --Matrix1 - Matrix2--
Result of Matrix1 - Matrix2 is :
0 1 0
1 0 1
0 1 0

salida 2

Enter the base of the matrices : 2
Enter the elements of the first matrix :
55 66
99 88
Enter the elements of the second matrix :
44 55
88 77
Subtracting Matrices --Matrix1 - Matrix2--
Result of Matrix1 - Matrix2 is :
11 11
11 11


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *