/*************************** MATRIX.CPP ***************************************
* Example showing how to use 2-dimensional arrays with functions                                                                         
* This program multiplies all elements in a matrix with a factor (scalar).                                                                          
* The program has the following sub-functions:                              
* ReadMatrix: reads matrix from keyboard input,                              
* WriteMatrix: writes matrix to screen,                                      
* MultiplyByScalar: multiplies matrix by scalar.                            
*                                                                            
* Note that when a function parameter is declared as an array, you actually  
* get a pointer, not a copy of the array. This means that you can modify    
* the array inside the function and the change has effect on the original    
* array outside the function.                                                

******************************************************************************/
#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();
}

Designed By Blogger Templates | Templatelib & Distributed By Blogspot Templates