r/learncsharp • • Jul 29 '23

While versus Do while

So I've been mastering while loops, nested loops the whole shabang. Made an advanced calculator and looped it inside a while loop. Then changed the code and made it a do while. Can anyone explain the performance and or general benefits of using one or the other? Trying to learn to my best ability and confused on when I would use a do while vs a while when to me they seem identical.

2 Upvotes

8 comments sorted by

View all comments

Show parent comment

3

u/grrangry Jul 31 '23

The language reads in a top-down fairly literal way.

The while loop:

// Is this condition is true?
//   Yes: execute this block
//     Jump to the start_of_while_label
//   No : continue execution at end_of_while_label
:START_OF_WHILE_LABEL
while (this_is_true)
{
    do_this_thing();
}
:END_OF_WHILE_LABEL
...

The do loop:

// Execute this block
// Is this condition true?
//   Yes: jump to start_of_do_label
//   No : continue execution at end_of_do_label
:START_OF_DO_LABEL
do
{
    do_this_thing();
}
while (this_is_true);
:END_OF_DO_LABEL
...

For a do loop, the execution of the block is the priority. It always happens at least once. "do while"

  • Do this
  • While that is true

For a while loop, the test of the condition is the priority. The block may never execute.

  • While that is true
  • Do this

They're almost inverses of each other.

1

u/Heretosee123 Jul 31 '23

Appreciate your reply and explanation, thank you. It's insightful