Search code examples
javascriptloopswhile-loopconditional-statementscycle

While loop, extra loop even though condition is false


I'm using javascript, but I'm looking for a general purpose solution that might apply to multiple languages.

I want to have a while loop that runs one time longer than it's supposed to.

For instance (assume the variables are defined above):

while (x != ">") {
    i++;
    tempStr += x;
    x = text[i];
}

So the output of the above code would have tempStr's last character be ">".

The important thing to remember, is that I'm not simply looking to do something like this:

while (x != ">") {
    i++;
    tempStr += x;
    x = text[i];
}
tempStr += x;

The above is just one example where it might be convenient to run the while loop for one final cycle after it's condition is false. And all though I can't share my actual code with you (for legal reasons), just know that the above wouldn't be a solution for the application I have in mind.

It might not be possible to do what I'm trying to do, if so, let me know :)


Solution

  •     while(condition || !extraLoopCondition) {
            //The usual stuff
            if(!condition) {
                extraLoopCondition = true;
            }
        }
    

    While it's not very eloquent, it will definitely do what you want it to

    Presumably the last cycle will have condition to be false at its end