English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Programmation orientée objet (I)

Java Programmation orientée objet (II)

Java Programmation orientée objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map (dictionnaire)

Java Set (ensemble)

Java Entrée/Sortie (I/O)

Lecteur Java/Écrivain

Autres sujets Java

Programme Java utilisant des tableaux multidimensionnels pour ajouter deux matrices

Java example summary

Dans ce programme, vous apprendrez à ajouter deux matrices en utilisant des tableaux multidimensionnels en Java.

Exemple : programme d'addition de deux matrices

public class AddMatrices {
    public static void main(String[] args) {
        int rows = 2, columns = 3;
        int[][] firstMatrix = {{2, 3, 4}, {5, 2, 3};};
        int[][] secondMatrix = {{-4, 5, 3}, {5, 6, 3};};
        //deux matrices additionnées
        int[][] sum = new int[rows][columns];
        for(int i = 0; i < rows; i++) {}}
            for (int j = 0; j < columns; j++) {}}
                sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
            }
        }
        //Display the result
        System.out.println("The sum of the two matrices is: ");
        for (int[] row : sum) {
            for (int column : row) {
                System.out.print(column + "  ");
            }
            System.out.println();
        }
    }
}

When running the program, the output is:

The sum of the two matrices is:
-2    8    7    
10    8    6

In the above program, the two matrices are stored in2In the d array, that is, firstMatrix and secondMatrix. We also define the number of rows and columns, and store them separately in the variables row and column

Then, we initialize a new array for the given row and column, called sum. This matrix array stores the addition of the given matrix.

We traverse each index of the two arrays to add and store the result.

Finally, we use the for (foreach variable) loop to traverse each element of the sum array to print the element.

Java example summary