For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
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!
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.
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:
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
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:
Here are some practical examples of Do While Loop in C for every skill 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:
Must EXplore: While Loop in Python
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:
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:
Must Read: Nested Loop in C
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.
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:
This example is common in login systems and secure access controls.
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:
This retry mechanism is often used in I/O operations, network requests, and resource management.
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. |
Let’s now compare both loops with practical C code to understand the functional difference.
#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:
#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 are some of the advantages of using the 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:
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:
#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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.