Combining different control flow blocks
And you might have been able to guess that we can combine any of the decision-making tools like if
, else
, and switch
within our while
loops and all the rest of the loops too. For example:
int x = 0; int tooBig = 10; while(true){ x++; // I am going to get mighty big! if(x == tooBig){ break; } // No you're not // code reaches here only until x = 10 }
It would be simple to go on for many more pages demonstrating the versatility of control flow structures but at some point, we want to get back to finishing the game.
Now we are confident with if
and else
, let's have a look at one more concept to do with loops. So here is one last concept combined with loops.
Continue...
The continue keyword acts in a similar way to break
- that we learned about in the previous chapter- up to a point. The continue
keyword will break out of the loop body but will also check the condition expression afterward so the loop could run again. An example...