/* Somme de deux matrices de int */ public class SommeMatrices { /* Fonction de creation d'une matrice de int */ /* initialise avec des nombres aleatoires */ /* compris dans l'intervalle [0,max] */ static int [][] initRandMatrice(int taille,int max) { int [][] tab = new int[taille][taille]; for ( int i = 0 ; i < taille ; i++ ) { for ( int j = 0 ; j < taille ; j++ ) { tab[i][j] =(int) (Math.random()*(max+1)); } } return tab; } /* Fonction d'affichage des valeurs contenues */ /* dans une matrice de int */ static void affichageMatrice(int [][] t) { int n = t.length; int m = t[0].length; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < m ; j++ ) { Ecran.formater("%5d",t[i][j]); } Ecran.sautDeLigne(); } } ///////////////////////////////////////////////// /* Fonction de calcul de la somme */ /* de 2 matrices de int de tailles compatibles */ /* m1 : La première matrice à sommer */ /* m2 : La seconde matrice à sommer */ /* ms : La matrice résultat */ static void somme(int [][] m1,int [][] m2,int [][] ms) { for ( int i = 0 ; i < m1.length ; i++ ) { for ( int j = 0 ; j < m1[0].length ; j++ ) { ms[i][j] = m1[i][j]+m2[i][j]; } } } /* Fonction de calcul et retour de la somme */ /* de 2 matrices de int de tailles compatibles */ /* m1 : La première matrice à sommer */ /* m2 : La seconde matrice à sommer */ static int [][] somme(int [][] m1,int [][] m2) { int [][] ms = new int[m1.length][m1[0].length]; somme(m1,m2,ms); return ms; } ///////////////////////////////////////////////// /* Programme principal */ public static void main(String [] args) { int taille; Ecran.afficher("Nombre de lignes et de colonnes ? "); taille = Clavier.saisirInt(); int [][] m1 = initRandMatrice(taille,999); int [][] m2 = initRandMatrice(taille,999); Ecran.sautDeLigne(); affichageMatrice(m1); Ecran.sautDeLigne(); affichageMatrice(m2); int [][] ms1 = somme(m1,m2); int [][] ms2 = new int[taille][taille]; somme(m1,m2,ms2); Ecran.sautDeLigne(); Ecran.afficherln("Somme par fonction avec retour"); affichageMatrice(ms1); Ecran.sautDeLigne(); Ecran.afficherln("Somme par fonction avec resultat en entête"); affichageMatrice(ms2); } }