'An integer array of up to 10 integers is read. Negative integers are not allowed to read

My program only allows positive integers up to 200 to be entered. -1 and the rest of negative numbers are not allowed to be read, and for safety, the 10th digit is not allowed to be read, program should stop reading. That is my code.

#include <stdio.h>

int main(void) {
    int age[10] = {0}; // initalized an array
    printf("Please enter ages: "); // allow user to enter numbers
    for (int i = 0; i < 10; i++) {
        if (age[i] == -1 || i > 9) { // if the element of is euqal to zero and 10th element
            printf("invalid number");
            break; // program stop
        }
        else if (age[i] < 0 || age[i] > 150 ){
            printf("It is invalid number, the valid number is bigger than 0 and smaller than 150");
            scanf("%d",&age[i]); // allow user enter again
        }
        else {
            scanf("%d",&age[i]);
        }
    }

    return 0;
}

The major question is that my code not stop reading when i enter the negative number.



Solution 1:[1]

Your program doesn't work, because you check if the numbers are negative, before you actually read them. Also, you check if i is greater than 9, which is redundant, since the for-loop already checks that. Finally, when the user enters an invalid number, you shouldn't just scanf a new one, because they might enter an invalid one again: you should instead run another iteration of the loop with the same i (decrease i by one and continue).

#include <stdio.h>

int main(void) {
    int age[10] = {0}; // initalized an array
    printf("Please enter ages: "); // allow user to enter numbers
    for (int i = 0; i < 10; i++) {
        printf("#%d: ",i);
        scanf("%d",&age[i]); // allow user enter again
        if (age[i] < 0 || age[i] > 150 ){
            printf("It is invalid number, the valid number is bigger than 0 and smaller than  151...\n");
            i--;
            continue;
        }
    }

    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1