What is Do While Loop in C- Embedded C Programming Training In Hyderabad

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Do While Loop in C

Lecture 8 of our free C programming course. Learn the exit-controlled do while loop in C, see how it differs from while, and test yourself with a quiz and embedded C interview questions covering the whole loop chapter.

The do while loop in C is the only loop that checks its condition after the body, which guarantees at least one pass. That single difference makes it the natural choice for menus, retry logic and input validation, all of which are everyday jobs in embedded C programming. This final lecture of the loop set in our free C programming course explains the syntax, compares do-while with while, works through four original examples, and ends with a quiz plus interview questions so you can check everything you learned in this free C tutorial series.

What You Will Learn

  • The syntax of the do while loop in C, with one statement and with a block.
  • What exit-controlled means and how it differs from the entry-controlled while loop.
  • Where a guaranteed first pass is the right design: retries, validation, digit counting.
  • How firmware uses do-while for hardware retry loops.
  • Common mistakes, especially the missing semicolon.
  • A ten-question quiz and ten interview questions on C loops.

Prerequisites

Finish the earlier lectures in this chapter first: the while loop, digit extraction, and the factorial and binary conversion lecture. You need to be comfortable tracing a loop by hand with a table of variable values.

Do While Loop Syntax in C

The keyword do opens the loop, the body follows, and the condition comes last inside while (...), ending with a semicolon. Use braces for several statements.

do
    single_statement;
while (condition);

do {
    statement_one;
    statement_two;
} while (condition);

That final semicolon is mandatory here, unlike in the plain while loop, where it is a mistake. Forgetting it causes a compile error, which is at least easy to spot.

How the Do While Loop Executes

The body runs first. Only then is the condition evaluated: true sends control back to the top of the body, false lets the program move on. Because the test is at the bottom, the loop is called exit controlled.

Flow of the do while loop in C

Enter loop
▼
Run the body once, always
▼
Test: is the condition true?
▲ TRUE, go back to the body▼ FALSE, leave the loop

While Versus Do While

Pointwhiledo while
Condition checkedBefore the body (entry controlled)After the body (exit controlled)
Minimum runs of the body01
Semicolon after the conditionNot allowed, creates an empty bodyRequired
Best forLoops that may not need to run at allRetries, menus, validation
Typical firmware usePolling a flag that might already be setSend and retry until acknowledged

Example 1: Seeing the Difference

Both loops below begin with a condition that is already false. Watch what each does.

#include <stdio.h>

int main(void)
{
    int level = 0;
    int whileRuns = 0;
    int doRuns = 0;

    while (level > 0)
        whileRuns++;

    do {
        doRuns++;
    } while (level > 0);

    printf("while ran %d times, do-while ran %d times\n", whileRuns, doRuns);
    return 0;
}
gcc -Wall -Wextra -std=c11 dw1.c -o dw1
./dw1
while ran 0 times, do-while ran 1 times

The do-while body ran once even though the condition was false from the start. That is the entire point of the loop.

Example 2: Retry Until Acknowledged

Communication code often sends a packet and checks for a reply. The first send has to happen no matter what, so a do-while loop fits. The attempt counter keeps the retry bounded.

#include <stdio.h>

int main(void)
{
    int tries = 0;
    int acked = 0;

    do {
        tries++;
        acked = (tries == 4);            /* pretend the receiver ACKs on the 4th send */
        printf("send attempt %d -> %s\n", tries, acked ? "ACK" : "NO ACK");
    } while (!acked && tries < 6);

    printf("Finished after %d attempts\n", tries);
    return 0;
}
send attempt 1 -> NO ACK
send attempt 2 -> NO ACK
send attempt 3 -> NO ACK
send attempt 4 -> ACK
Finished after 4 attempts

Retry loop state after each attempt

After attemptacked!acked && tries < 6Decision
10truerepeat
20truerepeat
30truerepeat
41falseexit

Example 3: Input Validation

To keep the program runnable without typing, the values a user might enter come from a small array. Replace the array read with scanf in a real program.

#include <stdio.h>

int main(void)
{
    int feed[] = {-5, 200, 42};          /* pretend the user typed these */
    int idx = 0;
    int percent;

    do {
        percent = feed[idx++];
        if (percent < 0 || percent > 100)
            printf("%d rejected, enter 0-100\n", percent);
    } while (percent < 0 || percent > 100);

    printf("Accepted %d%%\n", percent);
    return 0;
}
-5 rejected, enter 0-100
200 rejected, enter 0-100
Accepted 42%

Validation needs do-while because you cannot test a value that has not been read yet. With a plain while you would have to read once before the loop and again inside it, duplicating code.

Example 4: Fixing the Zero Digit Problem

In the digit-extraction lecture we saw that a while loop reports zero digits for the number 0. A do-while loop repairs that, because the first pass always counts one digit.

#include <stdio.h>

static unsigned int count_digits(unsigned int n)
{
    unsigned int count = 0;

    do {
        count++;
        n /= 10;
    } while (n > 0);
    return count;
}

int main(void)
{
    printf("digits in 0     = %u\n", count_digits(0));
    printf("digits in 7     = %u\n", count_digits(7));
    printf("digits in 90210 = %u\n", count_digits(90210));
    return 0;
}
digits in 0     = 1
digits in 7     = 1
digits in 90210 = 5

Do While in Embedded C Programming

  • Hardware initialisation: trigger a reset, then wait until a ready bit appears. The trigger must happen once regardless.
  • Retry logic: bus writes, flash programming and radio transmissions often need a bounded retry.
  • Menus on a serial console: show the menu once, read a choice, repeat until the user selects exit.
  • Multi-statement macros: you will meet do { ... } while (0) in many driver code bases. It makes a macro behave like a single statement, and it runs exactly once.

Common Mistakes and Troubleshooting

MistakeResultFix
Missing semicolon after while (condition)Compile errorEnd the statement with a semicolon
Using do-while when zero runs is validBody executes on bad dataUse while if the body must be skippable
Declaring a variable inside the body and using it in the conditionVariable is out of scope in the conditionDeclare it before the do
No limit on retriesHang when the device is deadAdd an attempt counter to the condition
Forgetting to update the loop variableInfinite loopChange something the condition reads

Best practices

Prefer while when zero iterations make sense, use do-while when the first pass is mandatory, always bound retry loops, keep braces on every body, and compile with warnings enabled. Add a comment explaining why do-while was chosen, because many readers expect a plain while.

Summary and Key Takeaways

Key takeaways

  • do-while tests the condition after the body, so the body always runs at least once.
  • The closing while (condition); needs a semicolon.
  • Pick it for retries, validation, menus and counting digits of zero.
  • Bound every retry loop in firmware.

Quiz: C Loops Practice

Try each question first, then open the answer. Questions cover the while loop, digit extraction, factorial, binary conversion and do-while.

  1. How many times does the body of while (0) { ... } run?
    • A) 0   B) 1   C) Infinite   D) Compile error
    Show answer

    A. The condition is false at the first test, so the body never runs.

  2. What does this print? int i = 1; while (i <= 3) { printf("%d ", i); i++; }
    • A) 1 2   B) 1 2 3   C) 1 2 3 4   D) 0 1 2
    Show answer

    B. It prints 1 2 3 and stops when i becomes 4.

  3. For n = 1452, how many iterations does while (n > 0) { n /= 10; } perform?
    • A) 3   B) 4   C) 5   D) 1452
    Show answer

    B. n becomes 145, 14, 1 and 0, which is four iterations.

  4. What should a product accumulator be initialised to?
    • A) 0   B) 1   C) -1   D) Any value
    Show answer

    B. One is the identity for multiplication; starting at 0 makes every product 0.

  5. What does int x = 3; while (x--) printf("%d ", x); print?
    • A) 3 2 1   B) 2 1 0   C) 3 2 1 0   D) 2 1
    Show answer

    B. The test uses the old value then decrements, so the body sees 2, 1 and 0. The loop stops when the tested value is 0.

  6. What is the minimum number of times a do-while body runs?
    • A) 0   B) 1   C) 2   D) Depends on the condition
    Show answer

    B. The condition is checked after the first pass.

  7. Which loop needs a semicolon after its closing condition?
    • A) while   B) do-while   C) both   D) neither
    Show answer

    B. do-while requires it; a semicolon after a plain while condition creates an empty body.

  8. Does 13! fit in an unsigned 32-bit integer?
    • A) Yes   B) No
    Show answer

    B. 13! is 6227020800, which is larger than 4294967295.

  9. What is the binary number 1101 in decimal?
    • A) 11   B) 12   C) 13   D) 14
    Show answer

    C. 8 + 4 + 0 + 1 equals 13.

  10. With k starting at 0, what does while (k < 3); { k++; } do?
    • A) Runs three times   B) Runs once   C) Loops forever   D) Does not compile
    Show answer

    C. The semicolon makes the loop body empty, so k never changes and the condition stays true.

Interview Questions on C Loops

1. What is the difference between entry-controlled and exit-controlled loops?

An entry-controlled loop (while, for) tests its condition before running the body. An exit-controlled loop (do-while) tests it afterwards, so it always executes at least once.

2. How do you write an infinite loop in embedded C, and why?

Use while (1) or for (;;). Bare-metal firmware has no operating system to return to, so the main loop never ends.

3. Why should every polling loop have a timeout?

If the hardware fails, an unbounded loop hangs the system forever. A counter or timer in the condition lets the code recover or report an error.

4. What does volatile do for a flag used in a loop condition?

It forces the compiler to read the variable from memory each time, which is required when an interrupt or hardware changes it.

5. How do you find the number of digits in an integer?

Divide by ten in a loop and count iterations. Use do-while so that zero correctly counts as one digit.

6. How would you detect overflow in a factorial loop?

Before multiplying, check whether fact is greater than the type maximum divided by the next factor. If it is, the product cannot fit.

7. What happens if you put a semicolon right after while (condition)?

The body becomes an empty statement. If the condition is true and nothing changes it, the loop never ends.

8. Why is signed integer overflow a problem?

It is undefined behaviour, so the compiler may optimise on the assumption that it never occurs, producing unpredictable results.

9. Why does do { … } while (0) appear in macros?

It turns several statements into a single statement that works safely inside if-else without braces, and it executes exactly once.

10. When would you choose while over do-while?

When running the body zero times is a valid outcome, for example processing a buffer that may be empty or polling a flag that may already be set.

Practice Challenges

  1. Write a program that prints the multiples of 7 up to 70 using a while loop.
  2. Count how many bits are set in the byte 0xB6 with a mask loop.
  3. Write a do-while loop that keeps a retry counter and gives up after eight attempts.

Conclusion

You now know all the repeat-until-done tools for this part of the chapter: the entry-controlled while loop, the exit-controlled do while loop in C, and the techniques of digit extraction, factorials and binary conversion built on top of them. The quiz and interview questions above are the kind that show up in embedded C programming screenings, so revisit any you missed. Our free embedded C course continues with the for loop, which packs initial value, condition and update into one line.

Frequently Asked Questions

When should I use a do while loop in C?

Use it whenever the body must run at least once, such as showing a menu, validating input or sending a packet before checking for an acknowledgement.

Is do while faster than while?

There is no meaningful speed difference. Choose based on whether the first pass is mandatory.

Why does do while end with a semicolon?

The whole do … while (condition) construct is one statement, and statements in C end with a semicolon.

Can I convert any do while loop to a while loop?

Yes, by duplicating the body before the loop or by using a flag, but the do-while form is usually cleaner.

Can a do while loop be infinite?

Yes, with a condition that is always true, such as do { … } while (1);, though while (1) is more common.

Do I need braces for a one-line do while body?

No, but braces are strongly recommended for readability and for safe later edits.

Next in the Free Embedded C Course

Move on to the for loop, then explore the Linux kernel and device driver lectures, all free on EmbeddedPathashala.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →