Code to multiply two matrices using for loop and 2d arrays -
L
Lanther X
Script Kiddie!
Below is the code for such program -
----
But I have some questions regarding some specific parts in the code. That is,
1) Why is there a third nested loop?
2) Can we write variable 'r1/r2' , 'c1/c2' instead of the integer "100" in array index below? -
#include <iostream>
using namespace std;
int main() {
int r1, c1, r2, c2;
// Input dimensions
cin >> r1 >> c1;
cin >> r2 >> c2;
// Check multiplication condition
if (c1 != r2) {
cout << "Matrix multiplication not possible";
return 0;
}
int A[100][100], B[100][100], C[100][100];
// Input first matrix
for(int i = 0; i < r1; i++) {
for(int j = 0; j < c1; j++) {
cin >> A[i][j];
}
}
// Input second matrix
for(int i = 0; i < r2; i++) {
for(int j = 0; j < c2; j++) {
cin >> B[i][j];
}
}
// Initialize result matrix
for(int i = 0; i < r1; i++) {
for(int j = 0; j < c2; j++) {
C[i][j] = 0;
}
}
// Matrix multiplication
for(int i = 0; i < r1; i++) {
for(int j = 0; j < c2; j++) {
for(int k = 0; k < c1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Output result matrix
for(int i = 0; i < r1; i++) {
for(int j = 0; j < c2; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}----
But I have some questions regarding some specific parts in the code. That is,
1) Why is there a third nested loop?
(int k = 0; k < c1; k++) 2) Can we write variable 'r1/r2' , 'c1/c2' instead of the integer "100" in array index below? -
A[100][100], B[100][100], C[100][100];