A fundamental part of any program is the ability to loop/repeat a set of tasks.
The while loop will repeatedly execute a set of instructions by first testing a condition before the instructions are executed.
The do…while loop will repeatedly execute a set of instructions by testing a condition after the instructions have been executed.
Consider the following scenario
If the number of people infected by a disease doubles every 10 days, how many days will it take until cases go from 100 to 1 million?
Example | Result |
---|---|
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 exampleNumber 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 |
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 |
Add Comment