C# Do While Loop - c# - c# tutorial - c# net




C# Do While Loop

C# Do While Loop

What is do while loop in C# ?

  • The do statement executes a statement or a block of statements repeatedly until a specified expression evaluates to false.
  • The body of the loop must be enclosed in braces, {}, if it consists of a single statement.
  • The difference between do..while and while is that do..while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.
 do while

Syntax:

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

C# Sample Code - C# Examples:

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;

namespace wikitechy_do_while_loop
{
classProgram
    {
staticvoid Main(string[] args)
        {
int n = 0;

do

            {
Console.WriteLine("value of n is: {0}", n);

                n = n + 1;
            }
while (n < 10);

Console.ReadLine();
        }
    }
}

Code Explanation:

 C for loop structure
  1. Hereint n = 0 is anintegervariable value as 0In this example do statement specifies the variable nwhich has0, thatturns out to be true for the condition n>10i.e. (0 > 10). Therefore, the loop continues.
  2. In this example Console.WriteLine,the Main method specifies its behavior with the statement "value of n is: {0}" to be displayed on the screen. Heren=n+1;specifies to n =0will increase by 1 each time the loop runs (n+1) variable till 9.If the while expression evaluates to true, execution continues at the first statement in the loop. If the expression evaluates to false, execution continues at the first statement after the do-while loop.
  3. Here Console.ReadLine(); specifies to reads input from the console. When the user presses enter, it returns a string.
 C do while loop strcture ouput
  1. Here in this output the statement "value of n is:5,6,7,8,9" specifies that the do while loop printed until it reaches the last element "9".

Related Searches to C# Do While Loop