C# do while loop

Description

do-while loops test the expression after the statement block has executed ensuring that the block is always executed at least once.

Syntax

do while loop has the following syntax.


do{
   statements;

}while(conditions);

Example

We can change the while loop to do while loop.


using System;/*from w ww. j  a va 2  s .  co m*/

class Program
{
    static void Main(string[] args)
    {
        int i = 5;

        do
        {
            Console.WriteLine(i);
            i--;
        } while (i > 0);

    }
}

The output:

Example 2

The following code displays the digits of an integer in reverse order with do...while loop.


using System; //  www .ja va 2  s. c  om
 
class MainClass {   
  public static void Main() { 
    int num; 
    int nextdigit; 
 
    num = 198; 
 
    Console.WriteLine("Number: " + num); 
 
    Console.Write("Number in reverse order: "); 
 
    do { 
      nextdigit = num % 10; 
      Console.Write(nextdigit); 
      num = num / 10; 
    } while(num > 0); 
 
    Console.WriteLine(); 
  }   
}

The code above generates the following result.

Example 3

Using break to exit a do-while loop


using System; /*from  w  w  w .  ja  v a2s .c  o m*/
 
class MainClass {  
  public static void Main() {  
    int i; 
 
    i = -10;     
    do { 
      if(i > 0) 
         break; 
      Console.Write(i + " "); 
      i++; 
    } while(i <= 10); 
  
    Console.WriteLine("Done");  
  }  
}

The code above generates the following result.

Example 4

The following code uses the do while statement to implement Newton's method for finding the square root of a number.


using System;/*w ww .j ava 2s .co m*/

public class MainClass {
   public static void Main( ) {
      double epsilon   = 1.0e-9;
      double guess    = 11.0;
      double result   = 0.0;

      double value = 2;

      result = ((value / guess) + guess) / 2; 

      do {
            Console.WriteLine( "Guess Value  = {0}", guess  );
            Console.WriteLine( "Result Value = {0}", result );
            guess = result;
            result = ((value / guess) + guess) / 2;
      } while( Math.Abs(result - guess) > epsilon );
      Console.WriteLine("The approx sqrt of {0} is {1}", value, result );
    }
}

The code above generates the following result.

Example 5

Do / while loop with a console read


using System;/*  www. ja v  a2s.  co m*/
using System.IO;

class MainClass
{
  public static void Main(string[] args)
  {
    string ans;
    do
    {
      Console.Write("Are you done? [yes] [no] : ");
      ans = Console.ReadLine();
    }while(ans != "yes");
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception