Search code examples
carraysloopsinitialization

C - Passing uninitialised variables to array elements


I'm wondering how do I handle uninitialised variables that I'm passing to another variable.

I am trying to write a program that at the end of it, after the user enters all the numbers, the highest and lowest numbers are shown.

int n[5], i, small, large;

for(i=0; i < 5; i++){

    printf("Enter number: ");
    scanf("%d", &n[i]);

    if(n[i] >= large){
        large = n[i];
    }
    else if (n[i] <= small){
        small = n[i];
    }

This produces the correct output (states the smallest number) but for the largest number, a random number is produced.

How can this be dealt with, besides initalising large to 0 (which will render the program inaccurate when negative numbers are entered)?

Thanks.


Solution

  • You have to initialize large to a really small value, and small to a really large value. You can use the limits defined in limits.h

    int small = INT_MAX, large = INT_MIN;