Lesson 5.3:

C# do while Loop - with programming example


Objective

What is do while loop in c#?
How it is different from while loop?
Programming example

What is do while loop in c#?

do while loop is another looping statement in c# which executes block of code and then evaluate condition. It ensures at least one execution of code. It is like a while loop only difference is while loop test the condition first then execute statement whereas do while loop execute the statement first then test condition.

Structure:

  do
  {
   statement(s);
  }
  while( condition );

		  
While(true) Loop

Programming Example

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

namespace do_while
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            do
            {
                Console.WriteLine("Hello Do While Loop");
                i++;
            }
             
            while (i < 10);
           
            Console.ReadKey();
        }
    }
}

		  

Output

Hello Do While Loop
Hello Do While Loop
Hello Do While Loop
Hello Do While Loop
Hello Do While Loop
Hello Do While Loop
Hello Do While Loop
Hello Do While Loop
Hello Do While Loop
Hello Do While Loop

__

Summary

Do while loop ensures at least one execution of code. It is very useful when you require at least one execution of program. Hope, you have learned it well. In the next chapter you will learn about for loop in c#.

BackNext