vendredi 25 mars 2016

If you have to put breaks in the if statements, why do we need to bother with conditions in the while operation?

This is just a general question really.

I wrote this originally

    do
    {
        scanf("%i", &Carselect);
        if (Carselect == 1)
        {
            mass = 1100;
            velomax = 200;
        }
        else if (Carselect == 2)
        {
            mass = 1888;
            velomax = 415
        }
        else if (Carselect == 3)
        {
            mass = 18000;
            velomax = 129;
        }
        else
        {
        printf("Error in input. Please enter 1, 2 or 3.\n");
        }
    }
    while (Carselect != 1 || Carselect != 2 || Carselect != 3);

And I got stuck in the loop. I put breaks in the statements for the valid conditions and that allowed me to get out, like this

    do
    {
        scanf("%i", &Carselect);
        if (Carselect == 1)
        {
            mass = 1100;
            velomax = 200;
            break;
        }
        else if (Carselect == 2)
        {
            mass = 1888;
            velomax = 415;
            break;
        }
        else if (Carselect == 3)
        {
            mass = 18000;
            velomax = 129;
            break;
        }
        else
        {
        printf("Error in input. Please enter 1, 2 or 3.\n");
        }
    }
    while (Carselect != 1 || Carselect != 2 || Carselect != 3);

but I thought that the conditions for while were repeat conditions, so as soon as Carselect equals 1, 2 or 3 it will exit the loop. If you have to put breaks in the if statements, why do we need to bother with conditions in the while operation?

What is there, on the machine level or otherwise, that requires this seemingly trivial bit of logic?

Aucun commentaire:

Enregistrer un commentaire