Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 483
heckascript Avatar asked Feb 26 '14 23:02

heckascript


2 Answers

    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

like image 56
user70585 Avatar answered Sep 23 '22 22:09

user70585


Yes, the do...while() construct is in most languages.

http://www.php.net/manual/en/control-structures.do.while.php

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
?>
like image 45
krowe Avatar answered Sep 21 '22 22:09

krowe