u

Thursday 7 June 2012

C++ Program for reading, writing and multiplication of the matrices

C++ Program for reading, writing and multiplication of the matrices



#include <iostream.h>
#include <iomanip.h>
#include <conio.h>

const int rows = 3;     // number of rows in matrix (must be constant)
const int columns = 3;  // number of columns in matrix (must be constant)

void ReadMatrix (float ma[rows][columns])
// this function reads matrix from keyboard
{
   int r, c;
   cout << "\nPlease enter matrix";
   for (r=0; r<rows; r++)
   {
      for (c=0; c<columns; c++)
      {
         cout << "\nElement A(" << (r+1) << "," << (c+1) << ") ";
         cin >> ma[r][c];
      }
   }
}

void WriteMatrix (float ma[rows][columns])
// this function writes matrix on screen
{
   int r, c;
   cout << "\nMatrix is:";
   for (r=0; r<rows; r++)
   {
      cout << "\n";
      for (c=0; c<columns; c++)
      {  // setw(10) adds space to make all numbers 10 characters wide
         cout << setw(10) << ma[r][c] << "  ";
      }
   }
}

void MultiplyByScalar (float sq[rows][columns], float fac)
// this function multiplies a matrix by a scalar
{
   int i, j;
   for (i=0; i<rows; i++)
   {
      for (j=0; j<columns; j++)
      {
         sq[i][j] = sq[i][j] * fac;
      }
   }
}              

void main ()
{
   // declare matrix and scalar
   float A[rows][columns], f;
   // get matrix from user
   ReadMatrix(A);
   // get scalar from user
   cout << "\n\nEnter factor ";
   cin >> f;
   // multiply matrix by scalar
   MultiplyByScalar (A, f);
   // output result matrix on screen
   WriteMatrix(A);
   // wait for user to press a key
   getch();
}

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More