C# do-while loop
C# do-while loop always execute block of code at least once, then check condition and repeat the loop as long as the condition is true.
C# do-while loop syntax
do
{
// block of code to be executed
}
while(condition)
In do-while loop first execute a block of code once an then check the condition, if condition is true as long as the code to be executed.
C# Example of do-while loop
int i=1;
do
{
Response.Write(i);
i++;
}
while (i <= 5);
The output is:
12345
In above c# do-while example, first set integer variable i=1, then execute do statement once and then check the while condition i<=5,
at initial i=1 directly execute do code print i.
Then increment 1 to i,
now i=2 the check while (i<=5) condition is true,
i=3 condition is true,
i=4 condition is true,
i=5 condition is true.
When i=6 the condition i<=5 is not true as 6 is not less than or equal to 5. The do-while loop result is : 12345
C# do-while example
int i=5;
do
{
Response.Write(i);
i--;
}
while (i >0);
The output is:
54321
Example – C# do-while loop
string name = "Meera Academy";
int i=1;
do
{
Response.Write("Hello " + name + "<br/>");
i++;
}
while (i <=5);
The output is:
Hello Meera Academy
Hello Meera Academy
Hello Meera Academy
Hello Meera Academy
C# do-while loop example
int i=1;
int sum = 0;
do
{
sum =sum+i;
i++;
}
while (i <=5);
Response.Write("The Sum of 1 to 5 =" + sum );
The output The Sum of 1 to 5 = 15
C# do-while loop Example
int i=1;
do
{
Response.Write(i);
i = i+2;
}
while (i <=10);
The output is : 13579
Example to display odd and even number using do-while loop.
string even="";
string odd="";
int i=1;
do
{
if(i%2==0)
{
even = even + " " + i ;
}
else
{
odd = odd + " " +i;
}i++;
}
while(i<=20);
Response.Write("The Even no = " + even + "<br/>");
Response.Write("The Odd no = " + odd);
The output is :
The Even no = 2 4 6 8 10 12 14 16 18 20
The Odd no = 1 3 5 7 9 11 13 15 17 19
Related ASP.Net Topics :
For Loop in C#.Net
While Loop in C#.Net
Subscribe us
If you liked this c#.net post, then please subscribe to our YouTube Channel for more c#.net video tutorials.
We hope that this asp.net c# tutorial helped you to understand about do-while loop.
Next asp.net tutorial we will learn about State Management in asp.net c#.