🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Do While Loop in C
Learn how the do while loop in C runs its body first, tests later and guarantees at least one pass. A hands-on lecture from our free C programming course for embedded systems.
The do while loop in C is the one loop that always runs its body before it asks any question. That makes it the right tool for prompts, retries and anything that must act first and judge second. This lecture is part of our free C programming course and free C tutorial, written for embedded C programming students who want clear rules and tested code.
Every program here was compiled with GCC and run, and the output shown is the real output. By the end you will know when a do while loop beats a while loop and how to keep it safe on hardware that never waits for you.
What You Will Learn
Prerequisites
- Lecture on the while loop in Chapter 5
- Relational and logical operators from Chapter 4
- GCC installed on Linux
Do While Loop in C: Syntax and Flow
A do while loop in C is an exit-controlled loop. The body sits first, the condition sits last, and the compiler guarantees that the body runs before the condition is ever looked at. That one rule is the whole personality of the loop. Here is the general form:
do {
statement1;
statement2;
} while (condition);
If the body is a single statement the braces are optional, but most teams keep them anyway. Notice the semicolon after the closing parenthesis. A plain while loop has no semicolon there, so this is the single most common typo when you switch between the two forms.
Read the diagram from the top. The body box comes before the decision box, which is exactly why a loop body can never be skipped on the first pass. After each pass the condition decides between another round and the exit.
| Part | Role | When it runs |
|---|---|---|
do | Marks the start of the loop body | Every time control enters or repeats the loop |
| Body in braces | The work to repeat | At least once, always before the first test |
while (condition) | Decides whether to repeat | After every pass of the body |
Trailing ; | Ends the statement | Compile time rule, required |
While vs Do While Loop in C
Both loops repeat code while a condition holds. They differ in where the test sits, and that changes what happens when the condition is already false at the start. A while loop is entry-controlled and may run zero times. A do while loop is exit-controlled and runs at least once.
The next program uses a fuel counter that starts at zero. The while loop never enters. The do while loop enters once, and then the test stops it.
#include <stdio.h>
int main(void)
{
int fuel = 0;
while (fuel > 0) {
printf("while: burning fuel\n");
fuel--;
}
do {
printf("do-while: checked once, then fuel=%d\n", fuel);
fuel--;
} while (fuel > 0);
printf("final fuel=%d\n", fuel);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o once once.c
./once
do-while: checked once, then fuel=0
final fuel=-1
Only the do while message appears, and the counter ends at -1 because the body decremented it before the test could object. That side effect is worth remembering: any action inside the body happens at least one time, even when the data is not ready.
| Property | while | do while |
|---|---|---|
| Condition checked | Before the body | After the body |
| Minimum executions | 0 | 1 |
| Semicolon after condition | No | Yes |
| Typical use | Count unknown, data may be absent | Prompt, retry, read-then-decide |
| Loop type name | Entry-controlled | Exit-controlled |
Counting Digits with a Do While Loop in C
Counting the digits of a number is a classic test of whether you chose the right loop. Dividing by ten removes one digit per pass. The value zero has one digit, but a loop that tests value != 0 first sees zero and exits with a count of zero. The do while form handles that edge case without a special if.
#include <stdio.h>
static int count_digits(unsigned int value)
{
int digits = 0;
do {
value /= 10;
digits++;
} while (value != 0);
return digits;
}
static int count_digits_while(unsigned int value)
{
int digits = 0;
while (value != 0) {
value /= 10;
digits++;
}
return digits;
}
int main(void)
{
unsigned int samples[] = {0, 7, 450, 98765};
int i;
printf("value do-while while\n");
for (i = 0; i < 4; i++) {
printf("%-7u %-10d %d\n", samples[i],
count_digits(samples[i]), count_digits_while(samples[i]));
}
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o digits digits.c
./digits
value do-while while
0 1 0
7 1 1
450 3 3
98765 5 5
Look at the first row. With the input 0 the do while version reports one digit, which is correct, and the while version reports zero. For every other value both agree. This is a real bug source in embedded code that formats numbers for a display or a UART log, so pick the loop that matches the data.
Reading Values Until a Stop Marker
Sensors and serial links often send a stream that ends with a marker value. A do while loop fits because you must read first and judge after. The program below sums integers from standard input and stops after it reads a zero. It also stops safely if the input runs out.
#include <stdio.h>
int main(void)
{
int reading;
int total = 0;
int count = 0;
do {
if (scanf("%d", &reading) != 1)
break; /* stop on bad input or end of data */
total += reading;
if (reading != 0)
count++;
} while (reading != 0);
printf("readings=%d total=%d\n", count, total);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o sumstop sumstop.c
echo "4 9 -2 0 77" | ./sumstop
readings=3 total=11
The numbers after the zero are never read, and the zero itself is added to the total but not counted as a reading. Feeding only a zero gives an empty result:
$ echo "0" | ./sumstop
readings=0 total=0
Why the scanf check matters
Without the scanf return test, bad input would leave reading unchanged and the loop could spin forever. Always handle the failure path of any input call inside a loop.
Input Validation and Retry Loops
Validation is where the do while loop in C earns its place. You must ask for a value before you can judge it, so a loop that tests first only works if you invent a fake initial value. The program below simulates five key entries and keeps asking until the ADC channel number falls between 0 and 7.
#include <stdio.h>
#define MIN_CH 0
#define MAX_CH 7
int main(void)
{
int typed[] = {12, -3, 9, 5, 2}; /* pretend user entries */
int next = 0;
int channel;
do {
channel = typed[next++];
if (channel < MIN_CH || channel > MAX_CH)
printf("channel %d rejected (valid %d-%d)\n", channel, MIN_CH, MAX_CH);
} while (channel < MIN_CH || channel > MAX_CH);
printf("ADC channel %d selected after %d entries\n", channel, next);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o retry retry.c
./retry
channel 12 rejected (valid 0-7)
channel -3 rejected (valid 0-7)
channel 9 rejected (valid 0-7)
ADC channel 5 selected after 4 entries
Three bad entries are rejected, the fourth is accepted, and the loop stops. In real firmware the entries would come from a UART or a button matrix, but the control flow is identical.
Menu Loops and Command Handlers
A console menu shows a prompt, reads a key and repeats until the user chooses to quit. The prompt must appear before any key exists, so the body-first order is natural. Here the key presses are scripted so you can run it without typing.
#include <stdio.h>
int main(void)
{
char script[] = "xyq"; /* pretend key presses */
int pos = 0;
char key;
do {
key = script[pos++];
printf("key '%c' -> ", key);
if (key == 'x') printf("start motor\n");
else if (key == 'y') printf("stop motor\n");
else printf("quit\n");
} while (key != 'q');
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o menu menu.c
./menu
key 'x' -> start motor
key 'y' -> stop motor
key 'q' -> quit
The loop ends only when the key is q, yet the quit branch still executes once, which is useful for printing a goodbye or releasing a resource inside the same body.
Where Embedded Engineers Use Do While Loops
| Situation | Why do while fits | Safety tip |
|---|---|---|
| Wait for a peripheral ready flag | Read the status register once, then decide | Add a timeout counter |
| Retry a flash or EEPROM write | Always attempt the write at least once | Cap the retries |
| Parse a variable-length packet header | Read a byte before you can test it | Check buffer bounds |
| Convert a number to text | Zero must still produce one character | Use a fixed-size buffer |
| Show a menu on a debug UART | Prompt appears before any input exists | Handle end of input |
Notice the pattern: every row begins with an action and ends with a judgment. When your problem has that shape, the do while loop in C says what you mean more directly than a while loop wrapped around a priming read.
Common Mistakes with Do While Loops
while (x < 10) without the final ; after a do body is a syntax error.while loop instead.continue skips the rest of the pass and goes straight to the condition. If the update statement sits below the continue, it is skipped and the loop can run forever.Best Practices
Habits that keep loops safe
- Choose do while only when the first pass is required, otherwise prefer while or for.
- Always use braces, even for one statement, so a later edit cannot break the structure.
- Put the condition update where a reader can see it, not buried after a continue.
- Bound every retry or wait loop with a counter or a timer.
- Compile with
-Wall -Wextraand read every warning.
Performance: a do while loop compiles to the same compare-and-branch pattern as other loops, so speed is not a reason to choose it. Safety: unbounded input loops are an availability risk, so a hostile or noisy source should never be able to hold a device inside a loop forever.
Key Takeaways
- A do while loop in C tests its condition after the body, so the body always runs at least once.
- The statement ends with a semicolon after the closing parenthesis.
- A while loop may run zero times, a do while loop never does.
- Digit counting, validation, retries and menus are natural fits.
- Always add an exit path to loops that depend on outside input.
Conclusion
The do while loop in C is small, but choosing it deliberately is a mark of careful code. When a task must act first and judge afterwards, this loop expresses that order without extra flags or duplicated statements.
Next you will meet the for loop in C, which packs setup, test and update into one line and is the workhorse for counted repetition in embedded programs.
Frequently Asked Questions
What is a do while loop in C?
It is an exit-controlled loop that runs its body first and then checks the condition, so the body executes at least once.
Why does a do while loop need a semicolon?
The whole do while construct is one statement, and C requires a semicolon to end it after the condition.
What is the difference between while and do while in C?
A while loop checks the condition before the body and may run zero times. A do while loop checks after the body and always runs once.
When should I use a do while loop in embedded C?
Use it for retries, readiness checks, input validation and any task where the first action must happen before the test.
Can a do while loop become infinite?
Yes, if the condition never turns false. Add counters or timeouts to loops that depend on hardware or user input.
What does continue do inside a do while loop?
It jumps to the condition test, skipping the rest of the current pass.
Is this lecture part of a free C programming course?
Yes. It belongs to our free C programming course for embedded systems, and every example was compiled and run.
Keep Learning Free Embedded C
Continue with the for loop in the next lecture of this free C programming course and free C tutorial for embedded C programming.

1 Comment