user3457524
user3457524

Reputation: 13

How to stop a while loop after looping x times

while(vowels != "NO" && vowels != "no" && vowels != "stop")
{
    vowels = prompt("Enter any vowel.");

    if (vowels != "a" && vowels != "A" && vowels != "e" && vowels != "E"
        && vowels != "i" && vowels != "I" && vowels != "o" && vowels != "O"
        && vowels != "u" && vowels != "U")
    {
        score+=-1;
    }
    else
    {
        score+=+1;
    }
}

How do I make it stop after 5 times?

Upvotes: 1

Views: 100

Answers (4)

Liam McInroy
Liam McInroy

Reputation: 4366

In your while conditional statement add:

var i = 0;
while(vowels != "NO" && vowels != "no" && vowels != "stop" && i < 5)
{
   ...
   i++;
}

This will add a tick counter to your loop. You could also use a for loop.

for loop example:

for (var i = 0; i < 5; i++)
{
    if (vowels != "NO" && vowels != "no" && vowels != "stop")
       break;
    vowels = prompt("Enter any vowel.");

    if (vowels != "a" && vowels != "A" && vowels != "e" && vowels != "E"
        && vowels != "i" && vowels != "I" && vowels != "o" && vowels != "O"
        && vowels != "u" && vowels != "U")
    {
        score+=-1;
    }
    else
    {
        score+=+1;
    }
}

Also, a classic example of a tick counter. :)

EDIT

As @DRAX pointed out, you could write the for as:

for (var i = 0; i < 5 && vowels != "NO" && vowels != "no" && vowels != "stop"; i++)
{
    vowels = prompt("Enter any vowel.");

    if (vowels != "a" && vowels != "A" && vowels != "e" && vowels != "E"
        && vowels != "i" && vowels != "I" && vowels != "o" && vowels != "O"
        && vowels != "u" && vowels != "U")
    {
        score+=-1;
    }
    else
    {
        score+=+1;
    }
}

This modifies the conditional of the for.

Upvotes: 1

kirilloid
kirilloid

Reputation: 14304

Feel the power of REGULAR EXPRESSIONS, TYPE COERCION and other 1337 $7UFF!

for (i = 0; i < 5; i++) {
    if(/^(no|NO|stop)$/.test(vowels)) break;
    score -= 1 - (/^[aeiou]$/i.test(vowels=prompt("Enter any vowel.")) << 1);
}

PS: do not try to repeat that at home.

Upvotes: 1

Simon
Simon

Reputation: 2960

    var cnt = 0;
    while(vowels != "NO" && vowels != "no" && vowels != "stop" && cnt <5)
    {
        cnt++;
        vowels = prompt("Enter any vowel.");

        if (vowels != "a" && vowels != "A" && vowels != "e" && vowels != "E" && vowels != "i"
        && vowels != "I" && vowels != "o" && vowels != "O" && vowels != "u" && vowels != "U")
        {
            score+=-1;
        }

        else
        {
            score+=+1;
        }

    }

Upvotes: 2

Martin Dinov
Martin Dinov

Reputation: 8825

One way to loop a specific number of times is to use a for loop. You could, for instance, wrap your while loop within a for loop that has 5 iterations.

Upvotes: -1

Related Questions