Exiting if loop inside of a while statement and starting over
in my else if statement, how do i make it start at the beginning of the while loop if number is lower or higher than guess?
16 Replies
continue
to go to the next iteration and break
to stop the loop, though you should't be using while(true)
Base the while on the exit condition
do-while if you don't want to check the exit condition before the first iterationif you dont break it then the while loop will start over from beginning (when all statements finished), and dont forget to put exit condition unless if u want make it infinitely loop
put continue and it will go back to first statement in while loop
Base the loop on guess == number
since you put the number is lower inside else statement, it will not execute if number is higher
Since there is no guess at the start, do-while to guess before evaluating and potentially exiting the loop
im so confused lol
if if statement is executed, the following else statement will not executed
mhm
so i guess in your case u can just omit the continue keyword
The continue approach works but is less readable. In general you want to avoid while(true) if you can
oh ok
Replacing true with an exit condition, such as number == guess, or in this case number != guess since you want to loop until it's equal
you can refactor it like for example:
bool isGuessTrue = false;
if (!isGuessTrue) { //some code eventually setting isGuessTrue to true}
That too will prevent evaluating the number when it's already been done
Starting with true, you just have to set it to false if < or >
I almost always use
while (true)
and then just use break
when the exit criteria are met. It's not a bad practice to use while (true)
for those kind of loops.
Because sometimes your exit criteria can be complex.