Unlock the Power of Matrices: A Step-by-Step Guide to Adding Two Matrices in C++
Understanding the Basics
Before diving into the code, it’s essential to review the fundamental concepts: C++ multi-dimensional arrays and C++ arrays. If you’re new to these topics, take a moment to brush up on the basics.
The Program: Adding Two Matrices
Our program prompts the user to input the number of rows (r
) and columns (c
) for two matrices. Note that the values of r
and c
should be less than 100.
int r, c;
std::cout << "Enter the number of rows: ";
std::cin >> r;
std::cout << "Enter the number of columns: ";
std::cin >> c;
Next, the user is asked to enter the elements of both matrices, which will be stored in two separate multi-dimensional arrays.
int matrix1[r][c], matrix2[r][c];
std::cout << "Enter elements of Matrix 1:\n";
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
std::cin >> matrix1[i][j];
}
}
std::cout << "Enter elements of Matrix 2:\n";
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
std::cin >> matrix2[i][j];
}
}
The Magic Happens
We’ll create a third matrix, also a two-dimensional array, to store the sum of the two input matrices.
int result[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
Then, we’ll display the resulting matrix on the screen.
std::cout << "Resultant Matrix:\n";
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
std::cout << result[i][j] << " ";
}
std::cout << "\n";
}
Example Output
Take a look at the example output below to see the program in action:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of Matrix 1:
1 2
3 4
Enter elements of Matrix 2:
5 6
7 8
Resultant Matrix:
6 8
10 12
Taking it to the Next Level
Ready for more? Check out our related article on multiplying two matrices using multi-dimensional arrays in C++. The possibilities are endless!
By mastering the art of matrix addition, you’ll unlock a world of possibilities in C++ programming. So, what are you waiting for? Start coding and take your skills to new heights!