You are on page 1of 8

Higher Dimensional

Arrays
Prepared By Dalton Ndirangu
6.4 Two-dimensional Arrays

 Arrays can have more than one dimension. In this section we briefly examine
the use of two-dimensional arrays to represent two-dimensional structures
such as nxm matrices of integers.
Pictorial interpretation
Example: Adding matrices
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
int mat1[10][10];
int mat2[10][10];
int mat3[10][10];

int m,n;
int i,j;

cout<<"Enter number of rows \n";


cin>>m;

cout<<"Enter number of columns\n";


cin>>n;

mat1[m][n];
mat2[m][n];
mat3[m][n];

cout<<"Enter data for first matric \n";


for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cin>>mat1[i][j];
}
}
Cont..
cout<<"Enter data for second matric \n";
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cin>>mat2[i][j];
}
}

//Adding matrices now

for(i=0; i<m; i++)


{
for(j=0; j<n; j++)
{
mat3[i][j]=mat1[i][j]+ mat2[i][j];
}

cout<<"Resultant Added matric is \n";

for(i=0; i<m; i++)


{
for(j=0; j<n; j++)
{
cout<<mat3[i][j]<< setw(4);
}
cout<<"\n";
}

system("pause");

return 0;
}
Example2: Multiplying matrices of two
varying dimensions
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
int mat1[10][10];
int mat2[10][10];
int mat3[10][10];

int m,n,p,q;
int i,j,k;

cout<<"Enter rows of first matric\n";


cin>>m;

cout<<"Enter columns of first matric\n";


cin>>n;

mat1[m][n];

p=n;

cout<<"Enter columns of second matric \n";


cin>>q;

mat2[p][q];

mat3[m][q];

cout<<"Enter data for first matric \n";


for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
cin>>mat1[i][j];
}
}
Cont..
cout<<"Enter data for second matric \n";
for(i=0; i<p; i++)
{
for(j=0; j<q; j++)
{
cin>>mat2[i][j];
}
}

//multiply now

for(i=0; i<m; i++)


{
for(j=0; j<q; j++)
{
mat3[i][j]=0;

for(k=0; k<n; k++)


{
mat3[i][j]+=mat1[i][k]*mat2[k][j];
}
}
}

cout<<"Resultant matric is \n";

for(i=0; i<m; i++)


{
for(j=0; j<q; j++)
{
cout<<mat3[i][j]<< setw(4);
}
cout<<"\n";
}

system("pause");

return 0;
}

You might also like