can someone explain what a do while statement is to me like im 5
Can anyone explain it to me? Thanks
5 Replies
The structure of a while loop is:
So it's as simple as you hit the
while
loop and the condition
gets evaluated. If it evaluates to true
then the code inside the braces will be executed. Once it reaches the closing brace it will go back and evaluate the condition
again, if it's true
it goes back into the braces and executes the code inside again, if it's false
it will jump past the while
loop and carry on executing whatever code comes after it
Inside the loop you can also put a break
or return
statement, which will make code execution break out of the loop without the condition
having to become false
sorry I just saw you said do-while is the same principle as above, except the condition
is evaluated at the end of the loop, meaning that the code inside will always be executed at least once, even if the condition
evaluates to false
What is the advantage of it over a for loop?
Well with a for loop you're generally going for a set number of iterations:
for (int i = 0; i < 10; i++)
Whereas a while
loop you're simply going until the condition you've set is no longer true, and the criteria for that condition could be updated in any number of ways rather than simply incrementing a number on each loopWith a
while
you can do something like
which will execute the loop as long as the random number it gets is less than 50
As soon as the number is 50
or 67
or 99
, the loop will stop executingOn general, you use a for loop if you have a known number of iterations, and while when you do not
You can "build" your own for loop using a while