Search results
Syntax. do { // code block to be executed} while (condition); The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
C# while loop. The while keyword is used to create while loop in C#. The syntax for while loop is: while (test-expression) { // body of while. } How while loop works? C# while loop consists of a test-expression. If the test-expression is evaluated to true, statements inside the while loop are executed.
As long as a condition tests true, C#'s while loop executes a block of code. This article explains how to code such a loop and what its features are.
A while loop is used for executing a statement repeatedly until a given condition returns false. Here, statements may be a single statement or a block of statements. The loop iterates while the condition is true. If you see the syntax and flow chart parallelly, then you will get more clarity of the while loop.
C# provides the while loop to repeatedly execute a block of code as long as the specified condition returns true. Syntax: While(condition) { //code block . } The while loop starts with the while keyword, and it must include a boolean conditional expression inside brackets that returns either true or false.
C# while statement examples. Let’s take some examples of using the while statement. 1) Simple C# while statement example. The following example uses the while loop statement to output five numbers from 1 to 5 to the console: int counter = 0; while (counter < 5) { counter++; Console.WriteLine(counter); } Code language: C# (cs) Output:
10 lis 2023 · An example. This program shows a while-loop. The while-keyword is followed by an expression. This expression must evaluate to a boolean value (true or false). Info The expression is evaluated each time the loop is encountered. If the result is true, the loop body statements are executed.