View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Understanding Do While Loop in C

Updated on 21/04/20253,042 Views

In C programming, understanding how loops work is essential. One of the most commonly used looping structures is the Do While Loop in C. This loop allows code to run at least once before checking a condition. It is especially helpful when the loop body must execute regardless of the condition. In this article, we will explore the working, syntax, and real-world usage of the Do While Loop in C. By the end, you'll know when and how to use it correctly in your programs.

We’ll begin with a clear definition of the loop, followed by its syntax and structure. Then, we'll walk through multiple examples, ranging from basic to advanced levels. We'll also discuss real-life use cases, compare it with the while loop, and highlight its pros, cons, and common mistakes. To finish, we’ll answer the most frequently asked questions. Let’s dive in and master the Do While Loop in C together.

If you want hands-on experience, consider enrolling in online software engineering courses offered by top universities!

What is Do While Loop in C?

The Do While Loop in C is a control flow structure used to repeat a block of code. Unlike other loops, such as the for loop and the while loop, the do while loop executes its code block first and then checks the condition. This means the loop will always run at least once, even if the condition is false.

This loop is especially useful when the initial execution must happen regardless of the condition. The test condition is evaluated after the loop body is executed. If the condition returns true, the loop runs again. If false, it terminates. Because of this behavior, it is known as an exit-controlled loop, unlike the while loop which is entry-controlled.

Syntax of Do While Loop in C

The Do While Loop in C uses a specific syntax that helps control the flow of execution. This loop always runs the code block at least once before it checks the condition. Understanding the syntax and its parts is important to use it correctly and avoid logical errors in C programming.

Here’s the syntax:

do {
// Code block to execute
} while (condition);

Explanation:

  • do keyword
    • This marks the beginning of the loop.
    • The code inside the block runs first; before any condition is checked.
  • { ... } block
    • This contains the actual code that you want to repeat.
    • You can write one or more statements inside these braces.
  • while (condition);
    • After executing the block, this condition is checked.
    • If the condition is true, the loop runs again.
    • If false, the loop stops.
    • The semicolon ; at the end is mandatory.

Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]

How Does the Do While Loop Work?

The Do While Loop in C works in a unique way compared to other loops. It always executes the loop body first before checking the condition. This means even if the condition is false from the beginning, the code block will still run once.

In other loops, such as the while loop and the for loop, the condition is evaluated before the loop body runs. But in a Do While Loop, the condition is checked after the block is executed. 

Here’s how the loop works step by step:

  1. The program enters the do block.
  2. It runs the code inside the block once.
  3. Then it checks the condition inside the while statement.
  4. If the condition is true, it goes back and runs the code again.
  5. If the condition is false, the loop ends.

Practical Example of Do While Loop in C

Here are some practical examples of Do While Loop in C for every skill level. 

Beginner Level

In this section, we will demonstrate how the Do While Loop in C works with a simple example. This will help beginners understand the flow of execution, starting from the loop’s first run. The following example will print numbers from 1 to 5 using a Do While Loop.

Here’s the code:

#include <stdio.h>

int main() {
int num = 1;

// Start of Do While Loop
do {
// Print the current value of num
printf("%d\n", num);

// Increment the value of num
num++;
} while (num <= 5); // Condition: Run the loop while num is less than or equal to 5

return 0;
}

Output:

1
2
3
4
5

Explanation:

  • int num = 1: Initializes the variable num with a value of 1. This will be printed in the loop.
  • do { ... } while (num <= 5): The body of the loop runs first, before checking the condition. The block prints num, then checks if num <= 5.
  • printf("%d\n", num): Prints the value of num in each iteration. This is the main action of the loop.
  • num++: Increments the value of num by 1 after each loop cycle. This helps the loop reach 5 and exit.
  • while (num <= 5): This condition checks whether num is less than or equal to 5. As long as it’s true, the loop runs. When num becomes 6, the loop stops.

Must EXplore: While Loop in Python

Intermediate Level

Now that you understand the basic structure of the Do While Loop in C, let’s move on to a more intermediate example. In this example, we will use the Do While Loop to repeatedly prompt the user to enter a number until they enter a valid, positive number. This will give you a better understanding of how you can interact with users and validate input.

Here’s the code:

#include <stdio.h>

int main() {
int number;

// Do While Loop to validate user input
do {
// Ask the user to input a positive number
printf("Please enter a positive number: ");
scanf("%d", &number); // Read user input

// Check if the number is positive
if (number <= 0) {
printf("Invalid input! Please try again.\n");
}

} while (number <= 0); // Loop continues if number is not positive

// If a positive number is entered, display it
printf("You entered a valid number: %d\n", number);

return 0;
}

Output:

Please enter a positive number: -5
Invalid input! Please try again.
Please enter a positive number: 0
Invalid input! Please try again.
Please enter a positive number: 12
You entered a valid number: 12

Explanation:

  • int number: Declares an integer variable number to store the user input.
  • do { ... } while (number <= 0): This Do While Loop will continue prompting the user until they enter a positive number. The loop runs first before checking the condition, ensuring that the user is always prompted.
  • printf("Please enter a positive number: "): Prompts the user to enter a number.
  • scanf("%d", &number): Reads the integer input from the user and stores it in the number variable.
  • if (number <= 0) { ... }: If the user enters a number less than or equal to zero, the program prints an error message and the loop continues.while (number <= 0): The condition checks if the number is less than or equal to 0. If true, the loop will repeat. If the user enters a valid positive number, the loop ends.
  • printf("You entered a valid number: %d\n", number): Once a positive number is entered, the program will display the number.

Advanced Level

At the Advanced Level, we explore more complex scenarios where the Do While Loop in C is useful. In this example, we will build a program that simulates a simple menu system. The user can select different options, and the program will repeatedly display the menu until the user decides to exit. This example demonstrates how the Do While Loop can be used to handle real-world scenarios like menus and user-driven choices.

Here’s the code:

#include <stdio.h>

int main() {
int choice;

// Do While Loop for Menu-driven program
do {
// Display menu options to the user
printf("Select an option:\n");
printf("1. Display Message\n");
printf("2. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice); // Read user input

// Handle different options based on user choice
switch(choice) {
case 1:
printf("Hello, welcome to the menu!\n");
break;
case 2:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice, please try again.\n");
}

} while (choice != 2); // Loop continues until user selects 'Exit'

return 0;
}

Output:

Select an option:

1. Display Message

2. Exit

Enter your choice: 1

Hello, welcome to the menu!

Select an option:

1. Display Message

2. Exit

Enter your choice: 3

Invalid choice, please try again.

Select an option:

1. Display Message

2. Exit

Enter your choice: 2

Exiting program.

Explanation:

  • int choice: Declares an integer variable choice to store the user's menu selection.
  • do { ... } while (choice != 2): This Do While Loop will continue running until the user selects option 2 (Exit). The loop executes the code first and then checks if the user’s input matches the exit condition.
  • printf("Select an option: ..."): Displays the menu options to the user.
  • scanf("%d", &choice): Reads the user input and stores the selected option in the choice variable.
  • switch(choice) { ... }: A switch statement is used to handle different options based on the user’s input. It provides a clear structure for managing multiple choices.
    • Case 1: Displays a welcome message.
    • Case 2: Exits the program by breaking the loop.
    • Default: Handles invalid inputs and asks the user to try again.
  • while (choice != 2): The loop will continue to prompt the user until the value of choice equals 2 (Exit). Once the user chooses to exit, the program terminates.

Must Read: Nested Loop in C

Use Cases of Do While Loop in Real Programs

The Do While Loop in C is not just useful for academic practice. It is widely used in real-world programs where at least one execution of a block of code is necessary before checking a condition. Unlike other loop types such as for or while, the do while loop guarantees a minimum of one execution, which makes it highly effective for user input validation, menu systems, retry logic, and interactive applications.

Let’s look at two practical use cases of the Do While Loop in C with real examples and detailed explanations.

Use Case 1: Validating User Input

In many programs, you must ask for user input and repeat the request until the user provides valid data. This is where a do while loop becomes essential.

#include <stdio.h>
#include <string.h>

int main() {
char password[20];

// Do While Loop to repeatedly ask for the correct password
do {
printf("Enter your password: ");
scanf("%s", password); // Take user input for password
} while (strcmp(password, "admin123") != 0); // Loop until correct password is entered

printf("Access granted.\n");

return 0;
}

Output:

Enter your password: hello
Enter your password: test
Enter your password: admin123
Access granted.

Explanation:

  • char password[20]: Declares a character array to store the input password.
  • do { ... } while (strcmp(password, "admin123") != 0): Keeps running until the correct password (admin123) is entered.
  • strcmp() function: Compares the user input with the actual password. If they don't match, it returns a non-zero value, and the loop continues.

This example is common in login systems and secure access controls.

Use Case 2: Retry Logic in File Access or Operations

When dealing with resources like files, databases, or devices, a program may need to retry an action if the first attempt fails.

#include <stdio.h>

int main() {
FILE *file;
int attempts = 0;

// Do While Loop to retry opening a file up to 3 times
do {
file = fopen("data.txt", "r"); // Try to open the file in read mode

if (file == NULL) {
printf("Attempt %d: Failed to open file. Retrying...\n", attempts + 1);
}

attempts++;

} while (file == NULL && attempts < 3); // Loop until file opens or attempts reach 3

if (file != NULL) {
printf("File opened successfully.\n");
fclose(file); // Always close the file when done
} else {
printf("Error: Could not open the file after 3 attempts.\n");
}

return 0;
}

Output:

Attempt 2: Failed to open file. Retrying...
Attempt 3: Failed to open file. Retrying...
Error: Could not open the file after 3 attempts.

Explanation:

  • FILE *file: Declares a pointer to a file object.
  • fopen("data.txt", "r"): Tries to open a file in read mode. If the file doesn't exist, it returns NULL.
  • Retry logic using do while: Retries opening the file a maximum of 3 times, printing a message on failure each time.
  • fclose(file): Closes the file if it opens successfully.

This retry mechanism is often used in I/O operations, network requests, and resource management.

Difference Between While and Do While Loop in C

The Do While Loop in C and the While Loop are both control flow structures used to repeat a block of code. However, they behave differently in how and when they evaluate conditions. Understanding these differences helps you choose the right loop for your use case.

Feature

While Loop

Do While Loop in C

Condition Check

Checked before the loop body

Checked after the loop body

Minimum Execution

May not execute even once

Executes at least once

Syntax Simplicity

Slightly simpler

Includes a semicolon after while()

Use Case

Best when pre-check is needed

Best when post-check is needed

Loop Entry Behavior

Enters only if condition is true

Enters first, then checks condition

Common Applications

Validating before execution

Menu-driven programs, retry logic, etc.

Code Demonstration: While vs Do While Loop

Let’s now compare both loops with practical C code to understand the functional difference.

Using While Loop

#include <stdio.h>

int main() {
int i = 1;

// While Loop: Condition is checked first
while (i < 1) {
printf("Inside while loop\n"); // This will NOT run
i++;
}

printf("Exited while loop\n");
return 0;
}

Output:

Exited while loop

Explanation:

  • The condition i < 1 is false from the start (i = 1).
  • Since the check happens before the loop body, the code inside never runs.
  • Only the final message after the loop is displayed.

Using Do While Loop in C

#include <stdio.h>

int main() {
int i = 1;

// Do While Loop: Code runs once before condition check
do {
printf("Inside do while loop\n"); // This WILL run once
i++;
} while (i < 1); // Condition is false, but only checked after 1st execution

printf("Exited do while loop\n");
return 0;
}

Output:

Inside do while loop
Exited do while loop

Explanation:

  • Here, the body of the do while loop runs once, even though the condition is false from the beginning.
  • This proves that do while ensures one execution before condition checking.
  • It is especially useful when you must run the code once no matter what, such as displaying a menu or asking for input.

Advantages of Using Do While Loop

Here are some of the advantages of using the Do While Loop:

  • Guaranteed First Execution: The loop body always executes once, even if the condition is false. This is ideal for input validation and menu-driven programs.
  • Clear Syntax for Post-Test Logic: Since the condition is checked after the code block, it helps implement scenarios where the action should happen before the decision.
  • Ideal for User-Driven Programs: Useful in programs that rely on user input, where you need to prompt the user at least once before continuing or exiting.
  • Easier to Write Repetitive Code with a Stop Condition: You can repeat a set of instructions and exit based on a logical stop condition after the initial execution.
  • Useful in Retry Mechanisms: In applications like login systems or retry prompts, the do while loop in C helps attempt the action before verifying continuation.
  • Avoids Redundant Condition Checks: If the task should always run once, using a while loop would require writing duplicate code outside the loop. A do while loop eliminates that.
  • Good Readability: It clearly separates the action from the condition check, making the program logic easier to follow.
  • Flexible in Real-Time Applications: It fits well in device polling, sensor reading, or buffer checking where the operation must run first before checking for data.

Disadvantages of Using Do While Loop

The Do While Loop is useful but comes with a few limitations. Knowing its drawbacks can help you choose the right loop structure for your program. Here are some of the main disadvantages of:

  • Code Executes at Least Once: The loop always runs once, even if the condition is false. This behavior may lead to unexpected results if not handled carefully.
  • Not Ideal for Pre-Check Logic: When the condition must be verified before running the code, a while loop or for loop is a better option.
  • May Cause Infinite Loops: If the condition is not updated correctly inside the loop, it can cause the program to run endlessly.Harder to Read in Complex Logic: In deeply nested or logic-heavy programs, the delayed condition check can confuse new programmers.
  • Less Common in Use: The do while loop is not used as frequently as for or while loops. Some developers may overlook its use or misuse it.
  • Debugging Can Be Tricky: Since the loop body runs first, tracing logic errors can take more time compared to other loop types.
  • Reduced Predictability: If the loop is placed before a condition is properly initialized, the output can become inconsistent or incorrect.

Challenges Faced While Using Do While Loop in C

While the Do While Loop is useful in many scenarios, it can still cause problems if not used properly. Beginners often face logic and syntax issues. Below are the most common challenges:

  • Condition Executes After the Loop Body
    • The loop body runs once before the condition is checked.
    • This can lead to unwanted output if the condition should be tested first.
  • Improper Condition Updates
    • If the control variable is not updated correctly, the loop may run infinitely.
    • Forgetting to increment or modify the condition can crash or freeze the program.
  • Difficult for Beginners to Predict Output
    • Many new programmers expect the loop to check the condition first, like a while loop.
    • This leads to confusion and unexpected results.
  • Hard to Use in Input Validation
    • If user input needs to be verified before use, a while loop is often safer.
    • The do while loop accepts input before validation, which may not be ideal.
  • Increased Risk of Logic Errors
    • Placing variables or statements incorrectly inside the loop may produce wrong results.
    • Errors become harder to debug when the loop executes even once with invalid conditions.
  • Reduced Flexibility in Certain Scenarios
    • When exit conditions are complex, managing the flow with do while becomes harder.
    • This can clutter the code and reduce readability.

Code Example: Infinite Loop Issue

#include <stdio.h>

int main() {
int i = 1;

// Infinite loop example due to missing increment
do {
printf("Value of i: %d\n", i);
// i++; // Increment is missing here
} while (i < 5);

return 0;
}

Output:

Value of i: 1
Value of i: 1
Value of i: 1
... (keeps printing)

Explanation:

  • The loop prints "Value of i: 1" endlessly.
  • This happens because “i” is never incremented.
  • The condition i < 5 remains true forever.
  • Adding i++; inside the loop would solve the problem.

Conclusion

The Do While Loop in C is a powerful control structure. It ensures that the code block runs at least once, regardless of the condition. This unique behavior makes it ideal for menu-driven programs, user input handling, and post-condition checks.

Before you implement it, always test your loop logic. This helps avoid infinite loops and logical bugs. When used correctly, the do while loop improves program flow and user experience.

If you’re still unsure when to use do while over while, just remember: Use do while when you want the loop body to execute at least once.

FAQs

1. What is a do while loop in C?

A do while loop in C is a post-test loop that executes its block at least once. The loop condition is checked after the first execution, making it useful for tasks that require initial execution before evaluation.

2. When should I use a do while loop instead of a while loop?

Use a do while loop when the code inside the loop must run at least once, regardless of the condition. This makes it ideal for user input validation or menu-based programs that require one-time display before checks.

3. Can a do while loop result in an infinite loop?

Yes, if the condition in a do while loop never becomes false, it can lead to an infinite loop. This usually happens when the loop variable isn’t updated correctly or the condition always evaluates to true.

4. Is it mandatory for the loop body to execute once in a do while loop?

Yes, the do while loop in C guarantees that the loop body executes at least once. This is because the condition is evaluated after the body, not before, making a first-time run mandatory every time.

5. What type of condition can be used in a do while loop?

The condition used in a do while loop should be a valid expression that evaluates to true or false. Typically, it involves comparison or logical operations and determines whether the loop should continue executing.

6. Can I use break and continue inside a do while loop?

Yes, the do while loop in C supports both break and continue statements. Break exits the loop immediately, while continue skips the remaining code in the loop and evaluates the condition again.

7. Are there any limitations to using do while loops in C?

One key limitation of a do while loop is that it may execute the loop body even when the condition is initially false. This can cause unexpected behavior if not handled carefully during program logic design.

8. How is a do while loop different from a for loop?

Unlike a for loop, a do while loop checks the condition after executing the block. A for loop is preferred for counter-controlled iterations, while do while suits cases where at least one execution is required.

9. Can I nest do while loops in C?

Yes, you can nest multiple do while loops in C. However, managing the logic inside nested loops requires careful planning, especially in terms of loop control variables and conditions to avoid infinite execution.

10. Is the semicolon necessary in a do while loop?

Yes, the semicolon after the condition in a do while loop is mandatory. Without it, the loop will result in a compilation error. It marks the end of the loop’s condition and is part of its syntax.

11. What happens if the condition in a do while loop is initially false?

Even if the condition is false, the do while loop will still execute the loop body once. This is the key difference from the while loop, which checks the condition before executing the loop body.

12. Is the do while loop faster than other loops in C?

The performance of a do while loop in C is generally similar to that of while and for loops. However, it can be more efficient when at least one execution is always required before any condition check.

13. Can I use functions inside a do while loop?

Yes, you can call functions within the body of a do while loop. This is useful when repeating a task like fetching user input, processing data, or running a routine multiple times based on a condition.

14. What is the main benefit of using a do while loop?

The main benefit of a do while loop is that it guarantees at least one execution of the loop body. This ensures the user sees output or a prompt before the condition is checked and evaluated.

15. Is do while loop suitable for all types of logic in C?

Not always. While do while loops are ideal for specific use cases, such as menu-driven programs, they may not be suitable for all logic. Sometimes, for or while loops provide better readability and control.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.