Hello Friends, In this tutorial, you are going to learn to do while loop in C#. We had already discussed for loop and while loop in C#. do while loop is very similar to while loop in C#.

After completing this tutorial you will be able to understand:

  • While loop in C#.
  • How to use do while loop in C#.
  • The difference between while and do while loop.

Introduction:

do while loop is similar to while loop except for the change that do while executes the specified code and then checks the condition. Another difference between while and do while loop is that do while loop executes for at least one time.

The syntax for declaring do while loop:


do
{
//block of code that needs to execute
}
while(condition);

do while

The condition appears at the end of the loop it means the loop iterates for at least one time. If the condition returns true the program flow returns to do.

An example of do while loop:

Open Visual Studio and create a Console Application called dowhileDemo.

do while

Write following code in Program.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace dowhileDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the No for which you want to print table");
int iNumber = Convert.ToInt32(Console.ReadLine());
int iCount = 1;
do
{
Console.WriteLine("{0} X {1} = {2}",iNumber,iCount,iNumber*iCount);
iCount++;
}
while(iCount<=10);
Console.ReadLine();
}
}
}

Run the application and look over the output window.

do while

Conclusion:

Hope you understand this tutorial. I will appreciate your feedback, comments and suggestions.

View More:

Thank You.

Leave a Comment