Home Basics C# do while loop

C# do while loop

The do…while loop likewise has the same syntax as in other languages derived from C. It is written in the following form:

do…while-loop ::= “do” body “while” “(” condition “)”
condition ::= boolean-expression
body ::= statement-or-statement-block

The do…while loop always runs its body once. After its first run, it evaluates its condition to determine whether to run its body again. If the condition is true, the body executes. If the condition evaluates to true again after the body has run, the body executes again. When the condition evaluates to false, the do…while loop ends.

Syntax

The syntax looks like this

do{  
//code to be executed  
}while(condition);

Here is what happens above

The code to be executed of the do…while loop is executed at first.
Then the condition is evaluated.
If the condition is true, the body of loop is executed.
When the condition is false, do…while loop terminates.

Example

Here is a do while example

using System;

public class Program
{
	public static void Main()
	{
		int i = 1;
		do
		{
			Console.WriteLine("i value: {0}", i);
			i++;
		} while (i <= 5);
		Console.WriteLine("Press Enter Key to Exit..");
		Console.ReadLine();
	}
}

When you run the following you will see the following

i value: 1
i value: 2
i value: 3
i value: 4
i value: 5
Press Enter Key to Exit..

using break

we can exit or terminate the execution of a do-while loop immediately by using the break keyword.

Here is an example of this

using System;

public class Program
{
	public static void Main()
	{
		int i = 1;
		do
		{
			Console.WriteLine("i value: {0}", i);
			i++;
			if (i == 5)
				break;
		} while(i < 10);
		Console.WriteLine("Press Enter Key to Exit..");
		Console.ReadLine();
	}
}

When you run this you will see the following

i value: 1
i value: 2
i value: 3
i value: 4
Press Enter Key to Exit..

nested loops

Again you can nest do while loops, here is an example of this

 

using System;

public class Program
{
	public static void Main()
	{
		int i = 1;
		do
		{
			Console.WriteLine("i value: {0}", i);
			i++;
			int j = 1;
			do
			{
				Console.WriteLine("j value: {0}", j);
				j++;
			} while (j <= 2);
		} while (i <= 4);
		Console.WriteLine("Press Enter Key to Exit..");
		Console.ReadLine();
	}
}

When run you will see the following

i value: 1
j value: 1
j value: 2
i value: 2
j value: 1
j value: 2
i value: 3
j value: 1
j value: 2
i value: 4
j value: 1
j value: 2
Press Enter Key to Exit..

Infinite do…while loop

Again its easy to create an infinite loop, I have read different opinions about this. Some say – never do this and others say its useful

do
{
	// body of while loop
} while (true);

 

You may also like