C# Do While Loop - c# - c# tutorial - c# net
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.
Syntax:
C# Sample Code - C# Examples:
Code Explanation:
- 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.
- 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.
- Here Console.ReadLine(); specifies to reads input from the console. When the user presses enter, it returns a string.
- 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".