0 votes
126 views
in Programming by (98.9k points)
edited
Write a program in c++ for addition of two matrices?

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer
#include <iostream>
using namespace std;

const int ROWS = 2;
const int COLS = 3;

void addMatrices(int m1[][COLS], int m2[][COLS], int result[][COLS]) {
 for(int i = 0; i < ROWS; i++) {
 for(int j = 0; j < COLS; j++) {
 result[i][j] = m1[i][j] + m2[i][j];
 }
 }
}

void printMatrix(int matrix[][COLS]) {
 for(int i = 0; i < ROWS; i++) {
 for(int j = 0; j < COLS; j++) {
 cout << matrix[i][j] << " ";
 }
 cout << endl;
 }
}

int main() {
 int matrix1[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}};
 int matrix2[ROWS][COLS] = {{6, 5, 4}, {3, 2, 1}};
 int result[ROWS][COLS];

 addMatrices(matrix1, matrix2, result);

 cout << "Matrix 1:" << endl;
 printMatrix(matrix1);

 cout << "Matrix 2:" << endl;
 printMatrix(matrix2);

 cout << "Result:" << endl;
 printMatrix(result);

 return 0;
}


In this program, we have defined a function addMatrices that takes two 2D integer arrays m1 and m2 as input and computes their sum, storing the result in another 2D integer array result.

We have also defined a function printMatrix that takes a 2D integer array matrix as input and prints it to the console.

In the main function, we have declared two 2D integer arrays matrix1 and matrix2 and initialized them with some values. We have also declared an empty 2D integer array result.

We then call the addMatrices function, passing matrix1, matrix2, and result as arguments.

Finally, we print the original matrices and the result matrix using the printMatrix function.

Output:

Matrix 1:
1 2 3 
4 5 6 
Matrix 2:
6 5 4 
3 2 1 
Result:
7 7 7 
7 7 7 

As we can see, the program successfully computes the sum of the two matrices and stores the result in result.

Related questions

0 votes
1 answer 157 views
0 votes
1 answer 1.3k views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

563 users

...