Multi-dimensional arrays
As well as holding simple lists, we may want to hold lists of lists, i.e. tables. To do this we can use
multi-dimensional arrays. These are arrays of arrays.
#include <stdio.h>
#define MHEIGHT 2
#define MWIDTH 2
void main()
{
/* read in and multiply 2 square matrices */
float Mat1[MHEIGHT][MWIDTH], Mat2[MHEIGHT][MWIDTH],
Mat3[MHEIGHT][MWIDTH];
int Count1, Count2, Count3; float Sum;
for (Count1=0; Count1<=(MHEIGHT-1); Count1++)
for (Count2 = 0; Count2 <= (MWIDTH-1); Count2++)
scanf("%f",&Mat1[Count1][Count2]);
for (Count1 = 0; Count1 <= (MHEIGHT-1); Count1++)
for (Count2 = 0; Count2 <= (MWIDTH-1); Count2++)
scanf("%f",&Mat2[Count1][Count2]);
for (Count1=0; Count1 <=(MHEIGHT-1); Count1++)
for (Count2=0; Count2 <=(MWIDTH-1); Count2++) {
Sum = 0;
for (Count3 = 0; Count3 <= (MWIDTH-1); Count3++)
Sum=Sum+Mat1[Count1][Count3]*Mat2[Count3][Count2];
Mat3[Count1][Count2] = Sum;
}
for (Count1 = 0; Count1 <= (MHEIGHT-1); Count1++) {
for (Count2 = 0; Count2 <= (MWIDTH-1); Count2++)
printf("%f ",Mat1[Count1][Count2]);
printf("\n");
}
for (Count1 = 0; Count1 <= (MHEIGHT-1); Count1++) {
for (Count2 = 0; Count2 <= (MWIDTH-1); Count2++)
printf("%f ",Mat2[Count1][Count2]);
printf("\n");
}
for (Count1 = 0; Count1 <= (MHEIGHT-1); Count1++)
for (Count2 = 0; Count2 <= (MWIDTH-1); Count2++) {
printf("%f ",Mat3[Count1][Count2]);
printf("\n");
}
}
Plain text to compile.
Exercises on this section.
Next - Structs.
Back to Contents page.