L-36 MCS 260 Mon 12 Nov 2001
Because Project Five requires two dimensional arrays, we introduce
matrices two lectures earlier than originally planned.
/* L-36 MCS 260 Mon 12 Nov 2001 : floating-point matrices
In this program we consider a floating-point matrix to store
information about terrain heights. Imagine we place an n-by-m
grid on a terrain. At each grid point, we measure the elevation.
Observe the following :
1) We use an intermediate function heights to achieve
the flexibility of variable dimensions of the matrix.
2) If we use arrays of variable dimensions in functions,
then we must pass the number of rows and columns.
3) In the function to find the peak, we initialize the maximum
as the first element in the matrix. */
#include<stdio.h>
/* we use the following function to allow the user to use any
number of rows and columns in the matrix : */
void heights ( int n, int m );
/* declares an n-by-m matrix of floating-point entries, reads in
the entries, looks for the highest peak */
int main ( void )
{
int rows,cols;
printf("Give number of rows : "); scanf("%d", &rows);
printf("Give number of columns : "); scanf("%d", &cols);
heights(rows,cols);
return 0;
}
/* all functions are local to the heights function and will not
be used in the main program, therefore we declare them as static : */
static void read ( int n, int m, float a[n][m] )
/* asks the user to provide the entries of an n-by-m floating matrix */
{
int i,j;
printf("Give entries of %d-by-%d matrix :\n", n, m);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
scanf("%f", &a[i][j]);
}
static void write ( int n, int m, float a[n][m] )
/* writes the entries of an n-by-m floating matrix to the screen */
{
int i,j;
printf("The entries of a %d-by-%d matrix :\n", n, m);
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
printf(" %f", a[i][j]);
printf("\n");
}
}
static float average ( int n, int m, float a[n][m] )
/* returns the average height of the terrain */
{
float sum = 0.0;
int i,j;
for (i=0; i<n; i++)
for (j=0; j<m; j++)
sum += a[i][j];
return (sum/(n*m));
}
static float peak ( int n, int m, float a[n][m], int *prow, int *pcol )
/* returns the maximal element in the n-by-m matrix a,
the coordinates of the maximum are in *prow and *pcol */
{
float max = a[0][0];
int i,j;
*prow = 0;
*pcol = 0;
for (i=0; i<n; i++)
for (j=0; j<m; j++)
if (a[i][j] > max)
{
max = a[i][j];
*prow = i;
*pcol = j;
}
return max;
}
void heights ( int n, int m )
{
float h[n][m],p;
int pr,pc;
read(n,m,h);
write(n,m,h);
printf("The average height : %f\n", average(n,m,h));
p = peak(n,m,h,&pr,&pc);
printf("The peak is %f at (%d,%d).\n", p, pr, pc);
}