What is a do while


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:
  1. 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
  1. 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

  1. 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
  1. 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 i: 0
value of i: 1
value of i: 1
value of i: 1




Post a Comment

0 Comments