0

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);

}
6
  • 1
    smallest = highest = randomNumbers[0]; is before randomNumbers[0] = rand() % (max - min + 1) + min;. Commented Sep 28, 2015 at 1:10
  • Also, if (i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i ==59 || i == 69 || i ==79 || i == 89) is not very maintainable. if (i % 10 == 9) does the same thing better. Commented Sep 28, 2015 at 1:11
  • Wouldn't putting it in the loop and after that store smallest and highest as the initial element of the array every time it goes through the loop though? Commented Sep 28, 2015 at 1:12
  • This is what debuggers are for. Commented Sep 28, 2015 at 1:13
  • It would, if you just plop it in. Good thing there is something that tells you whether this is your first run through the loop, or 99th. Or if you do as John Zwinck says, and do it in two separate loops. </hint> Commented Sep 28, 2015 at 1:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.