C
C#13mo ago
Array

can someone explain what a do while statement is to me like im 5

Can anyone explain it to me? Thanks
5 Replies
SinFluxx
SinFluxx13mo ago
The structure of a while loop is:
while (condition)
{
// code to be executed in each loop
}
while (condition)
{
// code to be executed in each loop
}
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 catfacepalm 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
Array
ArrayOP13mo ago
What is the advantage of it over a for loop?
SinFluxx
SinFluxx13mo ago
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 loop
Angius
Angius13mo ago
With a while you can do something like
while (Random.Shared.Next(100) < 50)
{
// ...
}
while (Random.Shared.Next(100) < 50)
{
// ...
}
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 executing
Pobiega
Pobiega13mo ago
On 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
Want results from more Discord servers?
Add your server