The do-while loop in C# is a control flow statement that executes a block of code at least once and then repeats the loop as long as a specified condition evaluates to true. It is similar to the while loop, but the key difference is that the condition is evaluated after the execution of the loop body, not before. Therefore, the body of the loop is guaranteed to execute at least once, even if the condition is initially false.
The do-while loop is similar to the while loop, but it checks the condition after each execution of its loop body. This type of loop is called a loop with a condition at the end (post-test loop). A do-while loop looks like this
The do-while loop is used when we want to guarantee that the sequence of operations in it will be executed repeatedly and at least once at the beginning of the loop.
Syntax:
do
{
// Code to be executed
} while (condition);
Explanation:
condition: This is a boolean expression that will be evaluated after each iteration of the loop. If the condition is true, the loop will continue. If the condition is false, the loop will terminate.
Note:
- The body of the loop is executed at least once regardless of the condition, because the condition is checked after the first iteration.
- If the condition is true, the loop continues to execute; if false, the loop ends.
Example:
using System;
class ProgramExample
{
static void Main()
{
int count = 1;
// do-while loop
do
{
Console.WriteLine("number: " + count);
count++; // Increment the counter
}
while (count <= 5);
}
}
Output:
number: 2
number: 3
number: 4
number: 5
Example: If we define count > 5 in the while loop then it will execute only one time.
using System;
class ProgramExample
{
static void Main()
{
int count = 1;
// do-while loop
do
{
Console.WriteLine("number: " + count);
count++; // Increment the counter
}
while (count > 5);
}
}
Output:
C# Do While loop – Interview Questions
Q 1: What is a do-while loop?
Q 2: Key difference between while and do-while?
Q 3: When is do-while loop used?
Q 4: Does do-while require semicolon?
Q 5: Can do-while be nested?
Do While loop – Objective Questions (MCQs)
Q1. When is the condition checked in a do-while loop?
Q2. What is the minimum number of times a do-while loop executes?
Q3. Which of the following is the correct syntax for a do-while loop?
Q4. Which keyword is used to exit a do-while loop prematurely?
Q5. Can a do-while loop run infinitely?