Taylor Jane
Taylor Jane

Reputation: 7

Populating array with random numbers/error with user defined function

My program crashed before anything was executed, except for the printf() statements of course. I'm also trying to include a user define function but I'm doing something wrong because it gave me the error that it was undefined, I had it above int main() but it still flagged the same error. I need random numbers to populate the array.

#include <stdio.h>
#include <stdlib.h>

#define ARR SIZE    25
#define MAXIMUM     100
#define MINIMUM     60

int main ()
{
int temp_sum;               //Initializes sum of all temperatures in order to calculate average total.
int temp_min, temp_max;     //Initializes minimum and maximum temperature variables.
int hour_count;             //Initializes actual hour of the day.
int temperature[25];        //Initializes array to have 25 elements.
int x, maximum, minimum;
float temp_avg;             //Sets variable to accept a decimal.

hour_count=0;

printf("Temperature Conditions on October 9th, 2015:\n");
printf("Time of Day \t \t Temperature in Degree Farenheit\n");

//Starts for loop to add one to each hour of the day.
for (hour_count=0; hour_count<=24; hour_count++)
    {

    if (temperature[x]>maximum)
        {
            temp_max=temperature[x];
            temp_max=x;
        }
    if (temperature[x]<minimum)
        {
            temp_min=temperature[x];
            temp_min=x;
        }

    printf("%d \t\t\t %d\n", hour_count, temperature);
    }

temp_sum=0;

for (x=0; x<=24; x++)
        {
            temp_sum=temp_sum+temperature[x];
        }
 temp_avg=temp_sum/25;


void GetValue(int value[], int x)
{

value[x] = (rand()%(100-60+1))+60;
}

printf("The maximum temperature for the day is %d degrees Farenheit.\n", temp_max);
printf("The minimum temperature for the day is %d degrees Farenheit.\n", temp_min);
printf("The average temperature for the day is %d degrees   Farenheit.\n", temp_avg);

return 0;
}

Upvotes: 0

Views: 35

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

In your code, all the variables used in the statement

  if (temperature[x]>maximum)

x, temperature[x] and maximum are uninitialized.

Being unitialized automatic local variables, their initial values are indeterminate. Any attempt to use the values will invokes undefined behavior.

Upvotes: 2

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

You use x before initializing it as an array index in the first loop. I guess you mean

if (temperature[hour_count] > maximum)

instead of

if (temperature[x]>maximum)

In your code, since x is not initialized when used undefined behavior will occur. In fact, the value of x is undeterminate at the moment you attempt to use it.

Upvotes: 0

Related Questions