Question #25700

Pls can i get a program to add 2 matrices

Expert's answer

#include <iostream>

#include <cmath>

using namespace std;

const int SIZE = 3;

typedef int Matrix[SIZE][SIZE];

void add_matrices(Matrix& a, Matrix& b, Matrix& result)

{

for (int i = 0; i < SIZE; i++)

for (int j = 0; j < SIZE; j++)

result[i][j] = a[i][j] + b[i][j];

}

void output_matrix(Matrix& a)

{

for (int i = 0; i < SIZE; i++)

{

for (int j = 0; j < SIZE; j++)

cout << " " << a[i][j];

cout << endl;

}

}

int main()

{

Matrix a = { { 3, 4, 0},

{ 0, 5, 1},

{ 8, 7, 2 } };

Matrix b = { { 2, 0, 1},

{ 6, 4, 4},

{ 0, 9, 1} };

Matrix result;

cout << "Matrix A:" << endl;

output_matrix(a);

cout << endl;

cout << "Matrix B:" << endl;

output_matrix(b);

cout << endl;

cout << "Result:" << endl;

add_matrices(a, b, result);

output_matrix(result);

return 0;

}

#include <cmath>

using namespace std;

const int SIZE = 3;

typedef int Matrix[SIZE][SIZE];

void add_matrices(Matrix& a, Matrix& b, Matrix& result)

{

for (int i = 0; i < SIZE; i++)

for (int j = 0; j < SIZE; j++)

result[i][j] = a[i][j] + b[i][j];

}

void output_matrix(Matrix& a)

{

for (int i = 0; i < SIZE; i++)

{

for (int j = 0; j < SIZE; j++)

cout << " " << a[i][j];

cout << endl;

}

}

int main()

{

Matrix a = { { 3, 4, 0},

{ 0, 5, 1},

{ 8, 7, 2 } };

Matrix b = { { 2, 0, 1},

{ 6, 4, 4},

{ 0, 9, 1} };

Matrix result;

cout << "Matrix A:" << endl;

output_matrix(a);

cout << endl;

cout << "Matrix B:" << endl;

output_matrix(b);

cout << endl;

cout << "Result:" << endl;

add_matrices(a, b, result);

output_matrix(result);

return 0;

}

## Comments

## Leave a comment