Write a C++ program that computes the sum of two square matrices using a two-dimensional array. Generate random values using the rand () function.
SAMPLE OUTPUT:
matrix 1
1
2
3
4
5
6
1
2
3
matrix 2
3
4
5
8
7
6
9
10
11
Sum of matrices is
4
6
8
12
11
12
10
12
14
#include <iostream>
using namespace std;
int main()
{
int firstM[3][3];
int secondM[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
firstM[i][j] = rand()%10;
secondM[i][j] = rand()%10;
}
}
cout<<"First matrix: \n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout<<firstM[i][j]<<" ";
}
cout<<endl;
}
cout<<"Second matrix: \n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout<<secondM[i][j]<<" ";
}
cout<<endl;
}
cout<<"Sum matrix: \n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout<<secondM[i][j]+firstM[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Comments
Leave a comment