Maxwell's Daemon - 1 year ago 73

C Question

I need to print out the result of a matrix multiplication using only system calls. I get the proper results but not in the appropriate format. I get 1000x1000 rows but I'd need 1000 colums x 1000 rows. Any idea how to do it?

This is the code I've written:

`#include <stdio.h>`

#include <string.h>

#include <stdlib.h>

#include <unistd.h>

#define N 1000

// Matrix

long long int A[N][N],B[N][N],R[N][N];

int main(int argc, char *argv[])

{

int x,y,z;

char str[100];

/* Matrix inicialization */

for(y=0;y<N;y++)

for(x=0;x<N;x++)

{

A[y][x]=x;

B[y][x]=y;

R[y][x]=0;

}

/* Matrix multiplication */

for(y=0;y<N;y++)

for(z=0;z<N;z++)

for(x=0;x<N;x++)

{

R[y][x]+= A[y][z] * B[z][x];

}

/* Printing result */

for(y=0;y<N;y++)

for(x=0;x<N;x++)

{

sprintf(str, "%lli\n", R[y][x]);

write(1, str, strlen(str));

}

exit(0);

}

Thanks in advance!

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Change the `sprintf()`

to separate numbers with spaces, and output a newline at the end of each row of the matrix:

```
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define N 1000
// Matrix
long long int A[N][N], B[N][N], R[N][N];
int main(void)
{
int x, y, z;
char str[100];
/* Matrix inicialization */
for (y = 0; y < N; y++)
{
for (x = 0; x < N; x++)
{
A[y][x] = x;
B[y][x] = y;
R[y][x] = 0;
}
}
/* Matrix multiplication */
for (y = 0; y < N; y++)
{
for (z = 0; z < N; z++)
{
for (x = 0; x < N; x++)
{
R[y][x] += A[y][z] * B[z][x];
}
}
}
/* Printing result */
for (y = 0; y < N; y++)
{
const char *pad = "";
for (x = 0; x < N; x++)
{
sprintf(str, "%s%lli", pad, R[y][x]);
write(1, str, strlen(str));
pad = " ";
}
write(1, "\n", 1);
}
return(0);
}
```

I have reservations about whether the matrix multiplication algorithm is correct; I get the same value (`332833500`

) printed for every cell.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**