C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: The code declares an integer array of 4 values. These are used inside the do-loop.
Part 2: A do-while loop is executed. The length of the array is not checked before adding the first element's value to the sum.
Part 3: This code would throw an exception if the array was empty. The array would be accessed out-of-range.
IndexOutOfRangeExceptionInfo: The while is executed after the code is run. No condition is tested before the statements in the loop are executed the first time.
C# program that uses do-while loop
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);
}
}
Output
31
Here: In these examples, we modify a for-loop. We turn it into a do-while loop. We see how the loops compare to each other.
For: This loop walks through the indexes 0, 1, 2, 3 and 4. The sum of these numbers is 10, which is the result of the SumFor method.
ForDo-while: This loop also walks through the indexes 0, 1, 2, 3 and 4. But it will evaluate the index 0 without checking any bounds.
While: The body statements of this loop are the same as in the do-while loop. It has the iteration statement at the start.
WhileC# program that uses 3 loops
using System;
class Program
{
static int SumFor()
{
int sum = 0;
for (int i = 0; i < 5; i++)
{
sum += i;
}
return sum;
}
static int SumDoWhile()
{
int sum = 0;
int i = 0;
do
{
sum += i;
i++;
} while (i < 5);
return sum;
}
static int SumWhile()
{
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());
}
}
Output
10
10
10
So: We know beforehand that the first iteration will always run. The do-while loop will avoid the first bounds check.
Note: This theoretically could be faster than another kind of loop, but in practice the do-while does not help.
C# program that runs first iteration in loop always
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);
}
}
Output
DO WHILE: 2
DO WHILE: 3
DO WHILE: 4
DO WHILE: 5
DO WHILE: 6
Also: The while-loop is the same as the do-while loop, but with the condition at the start.
Caution: The do-while loop is much less common. This makes errors due to human factors more likely.
So: It is likely that the JIT optimized the loops to the same machine instructions.