Looping – Do while loop

October20, 2017
by admin

Syntax:

do
{
  // statement or statements
  // to be executed
}while();

Lets have a look at the syntax of do while loop. It starts with ‘do’ keyword with no arguments. Then it has a body with opening and closing curly braces containing statements to be executed repeatedly. After closing curly brace, ‘while’ keyword is present with conditional expression within the parenthesis and semicolon describing the end of the do while loop statement.

The do while loop works very similar to the while loop with two major differences.

The first difference is that the condition is present at the end of the statement after the closing body of the loop rather than at the beginning of the loop.

The second major difference is that the ‘while’ loop may not execute at all if the conditional expression returns false at the first iteration. Whereas since the conditional expression is at the end of the body of ‘do while’ loop, it is guaranteed to be executed at least one time, even if the conditional expression returns false at the first iteration.

Lets have a look at the same example that we have discussed in the ‘while’ loop.

Ex:

Problem:

Write a program to display numbers from 1 to 10 in sequential order to console output each on separate lines.

Solution:


  using System;

  namespace LoopingDemo
  {
    public class DoWhileDemo
    {
      public static void main()
      {
        // counter variable declaration and initialization
        int x = 1;

        do 
        {
          // statement or statements to be executed
          Console.WriteLine(x);

          // increment/decrement counter variable
          x++; 
        }while(x <= 10);

        Console.WriteLine("Enter any key to exit : ");
        Console.ReadKey();
      }
    }
  }

Output:

1

2

3

4

5

6

7

8

9

10

Lets understand the code.

In the first line of coding we have declared and initialize the counter variable 'x' with initial value 1. This is similar to the 'while' loop.

int x = 1;

Then we started 'do while' loop with 'do' keyword with no arguments.

Immediately after 'do' keyword we have written the body of the 'do while' loop with an opening and closing curly braces.

do
{

The body part of the 'do while' loop is similar as that of the 'while' loop with no changes. Here we first write the statements to be executed repeatedly and then before closing the curly brace, we have incremented the value of the counter variable 'x' by 1 using increment operator (++).

After closing the curly brace of the 'do while' loop body, there is a 'while' keyword with the conditional expression within the parenthesis.

do
{

}while(x <= 10);

Note that at the of the 'while' statement there is a semicolon that denotes the end of the 'do while' loop.

When you compile and run the application, you will see the same result as of the 'while' loop example in the output section.

The code flow of the 'do while' loop is somewhat different than that of the 'while' loop. Let's understand it.

On the first line of code, the counter variable 'x' is declared with an integer data type and initial value of 1.

int x = 1;

Then control flow moves to the next statement that is 'do' keyword in the 'do while' loop. Since there is not a conditional
expression to check, the flow enters the body of the loop.

Here it executes the statements to be executed for each iteration of the loop. In this example, we have just printed the current value of variable 'x' to console output.

Console.Write1 Line(x);

After writing all code statements, before closing curly brace we have incremented the value of counter variable 'x' by 1 using increment operator.

x++;

After closing curly brace, we have written conditional expression with 'while' keyword as follows so that the loop will be repeated till the value of 'x' is less than or equal to 10.

}while(x <= 10);

We have used semicolon at the end of the 'do while' loop to denote the end of the loop.

This loop will execute 10 times from 1 to 10 and displays the values to the console output as expected.

After displaying the desired output, we have asked the user to press any key to exit the application.

Remember that though we have used the same example for a 'while' and 'do while' loop and the output is same for both loops, 'do while' loop executes at least once irrespective of the return value of conditional expression.

To demonstrate it, let's make some changes in the coding of both the loops.

Let's change the initialization value of the counter variable to 11 instead of 1.

int x = 11;

With this one change, compile and run both the applications.

The output of the 'while' loop will be blank with no values.

The output of the 'do while' loop will be a single value 11.

'while' loop output:

Press any key to exit: _

'do while' output:

11

Press any key to exit: _


Why is this happening?

In the 'while' loop, the conditional expression is executed at the beginning of the loop. So, since the value of x is 11 which is not less than or equal to 10, conditional expression returns false and while loop terminates without running for even once (one iteration).

In the 'do while' loop, though the initial value of counter variable 'x' is 11 which is not less than or equal to 10, since the conditional expression is at the end of the body, control flow enter the loop and executes once and print current value of x that is 11. After that it increments the value of 'x' by 1 and change it to 12. Then at the end of the first iteration it executes the conditional expression which returns false and terminate the loop.


When to use while loop and when to use do while loop?

Both while and do while loop have ability to give the expected output.

Use while loop for any scenario where you want to repeat statements till the specific conditional expression is true.

Use do while loop only when you want to execute statements at least once, irrespective of the return value of conditional expression.

C# Fundamentals