Reputation: 85
Part of my program is designed to output the smallest and largest values in an array stored with random numbers. My program outputs the largest value in the array just fine but when it comes to outputting the smallest value, it outputs some garbage. I've searched the website and I would figure it should work just fine based off what I have found. Here is my code I'd appreciate the help!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
int randomNumbers[100];
double average;
int highest, smallest;
int sum = 0;
int i = 0;
int min, max;
srand(time(NULL));
printf("Enter min and max respectively: ");
scanf("%d %d", &min, &max);
smallest = highest = randomNumbers[0];
for (i; i < 100; i++){
randomNumbers[i] = rand() % (max - min + 1) + min;
sum = sum + randomNumbers[i];
if (highest < randomNumbers[i]){
highest = randomNumbers[i];
}
if (smallest > randomNumbers[i]){
smallest = randomNumbers[i];
}
printf("%d ", randomNumbers[i]);
if (i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i ==59 || i == 69 || i ==79 || i == 89)
printf("\n");
}
average = sum / 100;
printf("\nAverage: %lf", average);
printf("\nHighest: %d", highest);
printf("\nSmallest: %d", smallest);
}
Upvotes: 0
Views: 1692
Reputation: 249093
The problem is your initialization:
smallest = highest = randomNumbers[0];
randomNumbers
has not yet been populated at that point. It might be clearer if you populated all the numbers first.
Upvotes: 2