C Do While loop

The do-while loop in C runs the code inside the loop once, and then checks the condition. If the condition is true, it repeats the loop; if the condition is false, the loop stops.

Syntax:


do {
    // Code to be executed
} while (condition);

Explanation:

  • do: Starts the loop and indicates that the code block inside the loop should execute.
  • Block of code: The code inside the curly braces { } will execute at least once before checking the condition.
  • while (condition): After executing the block of code, the condition is evaluated. If the condition is true, the loop will repeat; otherwise, it will terminate.

Example:


#include <stdio.h>

int main() {
     int count = 1;
        // do-while loop
        do
        {
            printf("number:%d\n", count);
            count++;  // Increment the counter
        }
        while (count <= 5);

    return 0;
}

Output:

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


#include <stdio.h>

int main() {
     int count = 1;
        // do-while loop
        do
        {
            printf("number:%d\n", count);
            count++;  // Increment the counter
        }
        while (count > 5);

    return 0;
}

Output:

1

C Do While loop – Questions and Answers

Q 1: What is a do-while loop in C?

Ans: A loop that executes at least once before checking the condition.

Q 2: Is do-while an exit-controlled loop?

Ans: Yes, the condition is checked after execution.

Q 3: What is the key difference between while and do-while?

Ans: do-while runs at least once; while may not.

Q 4: Is semicolon required after do-while?

Ans: Yes, a semicolon is mandatory.

Q 5: Where is do-while commonly used?

Ans: In menu-driven programs.

C do while loop – Objective Questions (MCQs)

Q1. What is the correct syntax of a while loop in C?






Q2. In a do-while loop, the condition is checked:






Q3. What is the output of this code?

int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 3);






Q4. Which statement about the do-while loop is true?






Q5. What is the output of this code?

int i = 5;
do {
printf("Hello ");
i++;
} while (i < 5);






Related C do while loop Topics