'Display two array elements in C
I need to show the matching "dates" element with the "values" element. I'm having trouble trying to show the two arrays' elements together. For example, I need to get the highest rainfall value to show the year and month it occurred. Same with lowest etc. I have used a for loop to find the highest and lowest values of rainfall that occurred but I am unsure on how to print the corresponding date.
I think I am on the right track but have gotten to this point and don't know what to do!
I would appreciate some help with this and maybe some tips to keep in my mind if you have any to share. P.S I'm new to stackoverflow.
My code so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Data Declaration
char header[40] = "";
int size_of_array = 768;
int dates[768] = {0};
float values[768] = {0};
float sum = 0;
float sum1 = 0;
float avg;
int i;
float largest, lowest;
FILE *input_fptr;
// Opens file
input_fptr = fopen("rainfallupdated.csv", "r");
if( input_fptr == NULL )
{
printf( "Error - could not open the file\n");
return 1;
}
// Read in the header line from file
fgets(header, sizeof(header), input_fptr);
printf("%s", header);
// Read 768 lines of data from the file
for( i=0; i < size_of_array; i++)
{
fscanf(input_fptr, "%d,%f\n", &dates[i], &values[i]);
printf( "%d\t %g\n", dates[i], values[i]);
}
fclose(input_fptr);
// Information for the user
printf("YearMonth , Rainfall in mm\n");
printf("\n");
printf("Example: 198702 -> February of 1987.\n");
printf("\n");
printf("--------------------------------------------------\n");
printf("--------------------------------------------------\n");
printf("\n");
// Total rainfall
for (i=0; i < size_of_array; i++)
{
sum = sum + values[i];
}
printf("Sum of all rainfall values -> %.2f mm\n", sum);
printf("\n");
// Average rainfall
avg = sum / size_of_array;
printf("Average rainfall value -> %.2f mm\n", avg);
printf("\n");
printf("--------------------------------------------------\n");
printf("--------------------------------------------------\n");
printf("\n");
// Largest and Lowest rainfall values
largest=values[0];
for(i=0; i < size_of_array; i++)
{
if(values[i]>largest)
largest=values[i];
}
lowest=values[0];
for(i=0; i < size_of_array; i++)
{
if(values[i]<lowest)
lowest=values[i];
}
printf("The highest rainfall value -> %.2f mm\n", largest);
printf("\n");
printf("The lowest rainfall value -> %.2f mm\n", lowest);
printf("\n");
/* for (i=0; i < 12; i++)
{
sum1 = sum1 + values[i];
}
printf("Total rainfall for 1958 -> %.2f mm\n", sum1); */
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
