Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Example

Result

Code Block
        static void Main(string[] args)
        {
            const int UPPER_LIMIT = 1000000;
            const int DAYS_INTO_VIRUS = 0;

            Console.WriteLine($"Number of days till virus reaches {UPPER_LIMIT} is {DaysToLimit( DAYS_INTO_VIRUS, UPPER_LIMIT) }");
        }

        static int DaysToLimit( int daysIntoVirus, int upperLimit )
        {
            int days = 0;
            const int FACTOR = 10;
            int virusCount = 1;

            while (days >= daysIntoVirus && virusCount <= upperLimit)
            {
                virusCount *= 2;
                days += FACTOR;
            }

            return days;
        }

while loop example

Number of days till virus reaches 1000000 is 200

It produces the correct result because the condition at line 15 can be satisfied. But changing the value of DAYA_INTO_VIRUS at line 4 will cause it to print out “Number of days till virus reaches 1000000 is 200” because the condition cannot be met

Code Block
    static void Main(string[] args)
    {
        const int UPPER_LIMIT = 1000000;
        const int DAYS_INTO_VIRUS = 5;

        Console.WriteLine($"Number of days till virus reaches {UPPER_LIMIT} is {DaysToLimit( DAYS_INTO_VIRUS, UPPER_LIMIT) }");
    }

    static int DaysToLimit( int daysIntoVirus, int upperLimit )
    {
        int days = 0;
        const int FACTOR = 10;
        int virusCount = 1;

        do
        {
            virusCount *= 2;
            days += FACTOR;
        }
        while (days >= daysIntoVirus && virusCount <= upperLimit);

        return days;
    }

do…while example

This works even with the erroneous value at line 4 because the actions in the loop are executed at least once before the condition is tested

Info

FAQ: How do I choose between using a while loop and a do...while loop? Ask yourself: if the while condition is already met before the first loop, do I want to go inside the loop anyway? If so, it's a do..while, otherwise it's a while loop.