TCUL
TCUL

Reputation: 13

scanf() and integer array

I'm trying to make a simple program which outputs the maximum value and minimum value from the user's input.

But it always takes one more input than I intend.

It seems to have a problem with scanf() but I'm not really sure.

int num, max = -100000, min = 1000000;

scanf("%d", &num);

int array[num];

for (int i = 0; i < num; i++) {
    scanf("%d ", &array[i]);
    if (max < array[i])
        max = array[i];

    if (min > array[i])
        min = array[i];
}

printf("%d %d", max, min);

Upvotes: 1

Views: 148

Answers (1)

chqrlie
chqrlie

Reputation: 144999

The trailing space in the format string scanf("%d ", &array[i]); causes scanf() to consume all newlines until you type something non blank, which you interpret as requiring an extra input. Remove this trailing space.

Also test the return value of scanf() to detect invalid input.

Furthermore, you do not need to store the values into an array.

Also note that -100000 and 1000000 are not safe initial values: what if all values typed by the user are below or above these thresholds? Use INT_MIN and INT_MAX or test the index value.

Here is a modified version:

#include <limits.h>
#include <stdio.h>

int main() {
    int i, num, val, max = INT_MIN, min = INT_MAX;

    if (scanf("%d", &num) == 1) {
        for (i = 0; i < num; i++) {
            if (scanf("%d ", &val) != 1) {
                printf("invalid input\n");
                break;
            }
            if (val < min)
                min = val;
            if (val > max)
                max = val;
        }
        if (i == 0) {
            printf("no values\n");
        } else {
            printf("%d %d\n", max, min);
        }
    }
    return 0;
}

Upvotes: 3

Related Questions