The C# while loop statement executes a statement or a block of statements until a specified expression evaluates to false . In some situation you may need to execute the loop at least one time and then check the condition. In this case you can use do..while loop.

The main difference between do..while and while loop is that do..while loop evaluates its expression at the bottom of the loop instead of the top. so, the statements within the do block are always executed at least once. From the following diagram you can understand how do..while loop function.

 do while Loop in c#

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int number, total, i;
 
            Console.WriteLine("Enter a Number");
            number = Convert.ToInt32(Console.ReadLine());
 
            i = 1; //Initialization
 
            do
            {
                total = number * i;
                Console.WriteLine("{0} x {1} ={2}", number, i, total);
                i++; //Increment by one
            }
            while (i <= 10); //Check  condition true or false
 
            Console.ReadLine();
 
        }
 
    }
}

 

Output:


 do while Loop in c#


Thanks.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like