Algorithm C. Why does the "why" string return and do not return numeric values?

2

I wrote an algorithm in C to write on the screen ordered pairs of a function, with input of x integers.

int main(int argc, char *argv[])
{
    int x,i;
    x = -1;

    do{
        system("cls");
        scanf("%i",&x);

        if(x>1000 || x <=0){
            printf("Entrada Invalida.");
            getch();
        }
    }while(x>1000 || x<=0);

    //scanf("%i",&x);
    float y[x];

    for(i=0;i<=x;i++){
        y[i]= pow(i,3) + pow(i,2) +i;
        printf("(%i,%.2f)\n",i,y[i]); 
    }
    system("PAUSE");    
    return 0;
}

I made constraints for input, but the constraints are just numeric. It turns out that with the previous code, if I type "why" instead of a number, I get the expected result: "Invalid input". But with the following code:

int main(int argc, char *argv[])
{
    int x,i;
    x = -1;
    //scanf("%i",&x);
    float y[x];

    for(i=0;i<=x;i++){
        y[i]= pow(i,3) + pow(i,2) +i;
        printf("(%i,%.2f)\n",i,y[i]); 
    }

    system("PAUSE");    
    return 0;
}

I get the following:

Whydoesthishappen?Whywiththerestriction,evenifitisjustnumeric,theresultis"Invalid Input"? Why, when there is no restriction, the program calculates values, even the input being string ("why")?

    
asked by anonymous 20.08.2017 / 22:31

1 answer

1

Your code is a bit confusing but I ran some tests and realized what happens. When you type "why" in the first code it can assign the upper bound of the integers which is 2 ^ 15-1 (32767) if you do not assign a value to X. This makes the if true because 32767 > 1000.

Or as "why" is an invalid value it holds -1, which also makes true if -1

21.08.2017 / 02:26