Search code examples
programming-languagesc#-4.0while-loopconditional-statements

What are the benefits of `while(condition) { //work }` and `do { //work } while(condition)`?


I found myself confronted with an interview question where the goal was to write a sorting algorithm that sorts an array of unsorted int values:

int[] unsortedArray = { 9, 6, 3, 1, 5, 8, 4, 2, 7, 0 };

Now I googled and found out that there are so many sorting algorithms out there! Finally I could motivate myself to dig into Bubble Sort because it seemed pretty simple to start with.

I read the sample code and came to a solution looking like this:

    static int[] BubbleSort(ref int[] array)
    {
        long lastItemLocation = array.Length - 1;
        int temp;
        bool swapped;

        do
        {
            swapped = false;
            for (int itemLocationCounter = 0; itemLocationCounter < lastItemLocation; itemLocationCounter++)
            {
                if (array[itemLocationCounter] > array[itemLocationCounter + 1])
                {
                    temp = array[itemLocationCounter];
                    array[itemLocationCounter] = array[itemLocationCounter + 1];
                    array[itemLocationCounter + 1] = temp;

                    swapped = true;
                }
            }

        } while (swapped);

        return array;
    }

I clearly see that this is a situation where the do { //work } while(cond) statement is a great help to be and prevents the use of another helper variable.

But is this the only case that this is more useful or do you know any other application where this condition has been used?


Solution

  • In general:

    • use do...while when you want the body to be executed at least once.
    • use while... when you may not want the body to be executed at all.

    EDIT: I'd say the first option comes up about 10% of the time and the second about 90%. You can always re-factor to use either, in either circumstance. Use the one that's closest to what you want to say.