Peaks And Valleys Code

#include <stdio.h>
#include <math.h>
#define N 25
#define FILENAME "grid1.txt"
int main(void)
{
/* Declare variables. */
int nrows, ncols, i, j, num_peaks=0, num_valleys = 0;
int highest, lowest;
int row_highest, row_lowest, col_highest, col_lowest;
double location =0;
double elevation[N][N];
FILE *grid;
/* Read information from a data file. */
grid = fopen(FILENAME,"r");
if (grid == NULL)
printf("Error opening input file\n");
else
{
fscanf(grid,"%d %d",&nrows,&ncols);
for (i=0; i<=nrows-1; i++)
for (j=0; j<=ncols-1; j++)
fscanf(grid,"%lf",&elevation[i][j]);
/* Determine and print peak locations. */
printf("Top left point defined as row 0, column 0 \n");
for (i=1; i<=nrows-2; i++){
for (j=1; j<=ncols-2; j++){
if ((elevation[i-1][j]<elevation[i][j]) &&
(elevation[i+1][j]<elevation[i][j]) &&
(elevation[i][j-1]<elevation[i][j]) &&
(elevation[i][j+1]<elevation[i][j])&& (elevation[i-1][j-1]<elevation[i][j]) &&
(elevation[i+1][j-1]<elevation[i][j]) && (elevation[i-1][j+1]<elevation[i][j]) &&
(elevation[i+1][j-1]<elevation[i][j])){
num_peaks = num_peaks + 1;
location = 100*sqrt(((5-i)*(5-i)) + (j*j));
printf("Peak at row: %d column: %d , which is %2.3lf feet from (0,0) \n",i,j, location);

}
}
}
printf("Number of peaks: %i \n", num_peaks);

for (i=1; i<=nrows-2; i++)
for (j=1; j<=ncols-2; j++)
if ((elevation[i-1][j]>elevation[i][j]) &&
(elevation[i+1][j]>elevation[i][j]) &&
(elevation[i][j-1]>elevation[i][j]) &&
(elevation[i][j+1]>elevation[i][j])&& (elevation[i-1][j-1]>elevation[i][j]) &&
(elevation[i+1][j-1]>elevation[i][j]) && (elevation[i-1][j+1]>elevation[i][j]) &&
(elevation[i+1][j-1]>elevation[i][j])){
num_valleys += 1;
location = 100*sqrt(((5-i)*(5-i)) + (j*j));
printf("Valley at row: %d column: %d , which is %2.3lf feet from (0,0) \n",i,j, location);


}
printf("Number of valleys: %i \n", num_valleys);
/* Close file. */
highest = elevation[0][0];
lowest = elevation[0][0];

for (i=0; i<=nrows-1; i++){
for (j=0; j<=ncols-1; j++){
 if (elevation[i][j]> highest){
highest = elevation[i][j];
row_highest = i;
col_highest = j;
                          }
 if (elevation[i][j]< lowest){
lowest = elevation[i][j];
row_lowest = i;
col_lowest = j;
}
}
}
printf(" Highest : %i is at row: %i and column: %i \n", highest, row_highest, col_highest);
printf(" Lowest : %i is at row: %i and column: %i \n", lowest, row_lowest, col_lowest);

fclose(grid);
}
return 0; /* Exit program. */
}

Comments

Popular posts from this blog

Seismic Code

Strings

BMP180 Code + Library to SD card