C++: calculer et afficher la somme d’une matrice

Author:

 calcul
Download


#include 
#include 
using namespace std;

int matrice[3][5] = { { 100, 500, 216, 112,  90 },
                     {  19, 200, 214, 111,  100 },
                     {  10, 115, 300, 316, 800 } };
int totalLigne[3];
int totalColonne[5];   

 int sommeMatrice( int v[][5], int len, int sommeLigne[], int sommeColonne[])
{
   int index_Ligne;   // Index des lignes
   int index_Colonne; // Index des colonne                   

   // calculer la somme des ligne
   for( index_Ligne = 0 ; index_Ligne < len ; ++index_Ligne)
   {
      sommeLigne[index_Ligne] = 0;
      for( index_Colonne = 0 ; index_Colonne < 5 ; ++index_Colonne)
        sommeLigne[index_Ligne] += v[index_Ligne][index_Colonne];
   }
   //Calculer la somme des colonnes
   for(index_Colonne = 0 ; index_Colonne < 5 ; ++index_Colonne)
   {
      sommeColonne[index_Colonne] = 0;
      for( index_Ligne = 0 ; index_Ligne < len ; ++index_Ligne)
        sommeColonne[index_Colonne] += v[index_Ligne][index_Colonne];
   }
   // Retourner le total de la somme
   return (sommeLigne[0] + sommeLigne[1] + sommeLigne[2]);
} 

int main()
{
   cout << "Calcul de la somme avec sommeMatrice()." << endl;

   int totalsum = sommeMatrice( matrice, 3, totalLigne, totalColonne);

   cout << "Voici la somme des lignes et colonnes de la matrice:" << endl;
   int i,j;
   for( i = 0 ; i < 3 ; ++i)
   {
     for( j = 0 ; j < 5 ; ++j)
       cout << setw(8) << matrice[i][j];
     cout << " | " << setw(8) << totalLigne[i] << endl;
   }
   cout << endl;
   for( j = 0 ;  j < 5  ;  ++j )
     cout << setw(8) << totalColonne[j];
   cout << " | " << setw(8) << totalsum << endl;
   return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *