Ads block

Banner 728x90px

c#step20


C# - do while

The do-while loop is the same as a 'while' loop except that the block of code will be executed at least once, because it first executes the block of code and then it checks the condition.
Syntax:
do
{
    //execute code block


} while(boolean expression);
As per the syntax above, do-while loop starts with the 'do' keyword followed by a code block and boolean expression with 'while'.
Example: do while loop
int i = 0;

do
{
    Console.WriteLine("Value of i: {0}", i);
    
    i++;

} while (i < 10);

Output:
Value of i: 0 
Value of i: 1 
Value of i: 2 
Value of i: 3 
Value of i: 4 
Value of i: 5 
Value of i: 6 
Value of i: 7 
Value of i: 8 
Value of i: 9
Just as in the case of the for and while loops, you can break out of the do-while loop using the break keyword.
Example: break inside do-while
int i = 0;

do
{
    Console.WriteLine("Value of i: {0}", i);
    
    i++;
    
    if (i > 5)
        break;

} while (true);

Output:
Value of i: 0 
Value of i: 1 
Value of i: 2 
Value of i: 3 
Value of i: 4 
Value of i: 5

Nested do-while

The do-while loop can be used inside another do-while loop.
Example: Nested do while loop
int i = 0;

do
{
    Console.WriteLine("Value of i: {0}", i);
    int j = i;

    i++;
                
    do
    {
        Console.WriteLine("Value of j: {0}", j);
        j++;

    } while (j < 2);

} while (i < 2);

Output:
Value of i: 0 
Value of j: 0
Value of j: 1
Value of i: 1
Value of j: 1
 Points to Remember :
  1. The do-while loop executes the block of code repeatedly.
  2. The do-while loop execute the code atleast once. It includes the conditional expression after the code block and the increment/decrement step should be inside the loop.
  3. Use the break keyword to stop the execution and exit from a do-while loop.
  4. An nested do-while loop is allowed.
Learn about C# structure next.

No comments:

Post a Comment