# Thread: How do I multiply two square matrices by 1 nested loop?

1. ## How do I multiply two square matrices by 1 nested loop?

I managed to print the matrix in one loop, but how can I multiply two matrices in 2 loops (1 nested loop), please help!!

Code:
```#include<iostream>
using namespace std;
#define size 4
int main()
{
int M[size][size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
int *ptrMatris = &M;
for (int i = 1; i <= 16; i++) {
cout << *ptrMatris++ << " ";
if (i % size == 0)
cout << endl;
}
return 0;
}``` 2. This way?
Code:
```void m4x4_mult( double *m, double *n, double *r )
{
int i, j;

for ( i = 0; i < 4; i++ )
for ( j = 0; j < 4; j++ )
{
r[i+4*j] = m[4*j]   * n[i]   +
m[4*j+1] * n[i+4] +
m[4*j+2] * n[i+8] +
m[4*j+3] * n[i+12];
}
}``` 3. yes, this way works but how can i write for any value of 0-10 not only 4. thanks... ) 4. You'll need a third loop for a variable square matrix dimensions... Popular pages Recent additions int, loop, matrices, multiply, nested 