The C# "do" keyword begins a loop. The loop body comes before its condition (which is specified in a while expression). Every looping construct has advantages.
This loop is rarely needed—it probably has more disadvantages than advantages. We use the do-while
loop (but we probably should not).
First we use the do-while
loop to sum the values of the elements in an int
array. The array here is known to have 4 elements, so we can avoid checking its length.
do
-loop.do-while
loop is executed. The length of the array is not checked before adding the first element's value to the sum.class Program { static void Main() { // Part 1: new int array. int[] ids = new int[] { 6, 7, 8, 10 }; // Part 2: use do-while loop to sum numbers in 4-element array. int sum = 0; int i = 0; do { // Part 3: add to sum. sum += ids[i]; i++; } while (i < 4); System.Console.WriteLine(sum); } }31
In C# the most common type of loop is probably the for
-loop. It allows you to specify the 3 conditions right at the start.
for
-loop—we turn it into a do-while
loop. We see how the loops compare to each other.SumFor
method.do-while
loop. It has the iteration statement at the start.using System; class Program { static int SumFor() { // Version 1: for loop. int sum = 0; for (int i = 0; i < 5; i++) { sum += i; } return sum; } static int SumDoWhile() { // Version 2: do-while loop. int sum = 0; int i = 0; do { sum += i; i++; } while (i < 5); return sum; } static int SumWhile() { // Version 3: while loop. int sum = 0; int i = 0; while (i < 5) { sum += i; i++; } return sum; } static void Main() { Console.WriteLine(SumFor()); Console.WriteLine(SumDoWhile()); Console.WriteLine(SumWhile()); } }10 10 10
Consider this program: it starts its iteration variable (value) at a constant. And it continues until the constant value 6 is reached.
do-while
loop will avoid the first bounds check.do-while
does not help.using System; class Program { static void Main() { // We start at a constant, so we know the first iteration will always be run. // ... This reduces the number of checks by 1. int value = 1; do { value++; Console.WriteLine("DO WHILE: " + value); } while (value <= 5); } }DO WHILE: 2 DO WHILE: 3 DO WHILE: 4 DO WHILE: 5 DO WHILE: 6
The critical difference between the for loop and the do-while
loop is that in do-while
, no conditions are checked before entering the loop.
while
-loop is the same as the do-while
loop, but with the condition at the start.This difference in the first iteration is important. All other loops have a test before the first iteration. Think about the first iteration carefully.
do-while
loop is much less common. This makes errors due to human factors more likely.It is reasonable to avoid do-while
loops—they are less familiar to developers. For most situations, using for
-loops in all possible places is probably best.