While Loop Interview Questions for Embedded C: Quiz and Code Challenges-Free Embedded C Training in Hyderabad

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

MODULE 7 · LESSON 7.2 · PRACTICE

While Loop Interview Questions for Embedded C: Quiz and Code Challenges

56 questions: multiple choice, write-the-loop blanks, a loop-matching table, true/false, 6 code challenges and 12 detailed interview answers. Treat it as a model for while loop interview questions.

56
Questions
Beginner → Advanced
Level
Live score
Auto-graded
Live Score Tracker
0
Correct
0
Wrong
0
Attempted
Answer the auto-graded questions (MCQ, fill-in, true/false) to see your score.

Section 1: Multiple Choice Questions — while and do-while

These while loop interview questions in multiple-choice form are common in written screening tests. Click an answer; explanations always appear.

1. How many times does the body of while (0) { ... } run?

2. How many times does the body of do { ... } while (0); run?

3. Which loop tests its condition after the body?

4. What is required after the condition of a do-while?

5. Which loop is best for waiting until a status flag is set?

6. Why must a polled hardware register be accessed through a volatile pointer?

7. What does while (1) do?

8. What is the purpose of a timeout in a polling loop?

9. What does a semicolon directly after while (x > 0) do?

10. What is a sentinel value?

11. Why is do { … } while (0) used in macros?

12. For the number 0, which loop gives a correct integer-to-text conversion?

13. A flag is set by an ISR; main waits with while (!ready);. What is missing?

14. Which statement is true about a for loop and a while loop?

15. What is the main drawback of busy-waiting in a battery product?

Section 2: Write or Evaluate (Fill in the Blanks)

Type the code for the first three items (spacing is flexible) and a short value for the rest.

1. Write the header of an endless while loop:

2. Write the line that closes a do-while whose condition is n > 0 (starting with the closing brace):

3. Write a polling loop header that waits while bit 7 of SR is clear (header only, ending with the condition):

4. int n = 3, s = 0; while (n > 0) { s += n; n--; } gives s =

5. int n = 0; do { n += 5; } while (n < 5); gives n =

6. int i = 0; while (i++ < 3); leaves i =

7. unsigned x = 40; int k = 0; while (x > 1) { x /= 2; k++; } gives k =

8. A do-while body with an always-false condition runs time(s)

Section 3: Which Loop Fits?

Choose the loop form for each task, as asked in while loop interview questions about design.

TaskYour answerResult
Wait for the ADC end-of-conversion flagwhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)
Convert the number 0 to textwhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)
Copy a string up to its NULwhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)
Retry a sensor read up to 3 timeswhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)
Main program that never returnswhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)
Process 8 bits of a bytewhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)
Empty a receive ring bufferwhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)
Macro with several statementswhile with a timeoutdo-whilewhile on a sentineldo-while with a retry limitwhile (1)for with a counterwhile on the pop resultdo { } while (0)

Section 4: True or False

Statements typical of while loop interview questions.

1. A while loop may execute its body zero times.

2. A do-while loop may execute its body zero times.

3. while (x = 0) is a loop that runs forever.

4. while (1) and for (;;) are equivalent infinite loops.

5. A volatile qualifier is unnecessary when polling a memory-mapped status register.

6. Putting a timeout into a polling loop makes the program larger but safer.

7. while (n--) with unsigned n = 0 eventually ends.

8. In a for loop continue skips the update expression.

Section 5: Code Snippet Challenges

Trace each program on paper first; the real output follows. These challenges are the code-reading half of while loop interview questions.

Challenge 1 — Output?: Post-increment in the condition
#include <stdio.h> int main(void) { int i = 0; while (i++ < 3) printf(“%d “, i); printf(“| %d\n”, i); return 0; }

What are the printed values?

Output:
1 2 3 | 4
The test uses the old value and increments afterwards: it prints 1 2 3; the fourth test (3 < 3) is false but i still becomes 4.
Challenge 2 — Output?: do-while with a decrement
#include <stdio.h> int main(void) { int x = 5; do { printf(“%d “, x); x -= 2; } while (x > 0); printf(“| %d\n”, x); return 0; }

What are the printed values?

Output:
5 3 1 | -1
x = 5, 3, 1 are printed; after the pass with 1, x becomes -1 and the test fails.
Challenge 3 — Find the bug: Semicolon after while
#include <stdio.h> int main(void) { int n = 0; while (n < 3); { n++; } printf(“%d\n”, n); return 0; }

What happens when this program runs? (Do not run it.)

Result: the program hangs. The semicolon is the loop body, so n never changes and n < 3 stays true forever; the block after it is never reached. GCC’s -Wmisleading-indentation may not warn here because the block is a separate statement.
Challenge 4 — Output?: while (*s++)
#include <stdio.h> int main(void) { const char *s = “ab”; int count = 0; while (*s++) count++; printf(“%d\n”, count); return 0; }

What is printed?

Output:
2
The loop counts the characters before the NUL: 2. Afterwards s points one past the NUL, because the post-increment happens even for the failing test.
Challenge 5 — Output?: Unsigned countdown
#include <stdio.h> int main(void) { unsigned n = 3; while (n– > 0) printf(“%u “, n); printf(“| %u\n”, n); return 0; }

What is printed?

Output:
2 1 0 | 4294967295
The test uses the old value: n = 3, 2, 1 pass and the body sees 2, 1, 0. The test with the old value 0 is false but still decrements n to 4294967295.
Challenge 6 — Output?: Euclid’s algorithm
#include <stdio.h> int main(void) { int a = 48, b = 18; int steps = 0; while (b != 0) { int t = a % b; a = b; b = t; steps++; } printf(“%d %d\n”, a, steps); return 0; }

What are the gcd and the number of passes?

Output:
6 3
(48,18) → (18,12) → (12,6) → (6,0): three passes, gcd 6.

Section 6: While Loop Interview Questions for Embedded C (with Detailed Answers)

While loop interview questions test polling, volatile, termination and the design of the main loop. Click a question for a model answer.

Q1. What is the difference between while and do-while? Give a use case for each.Basic+

while tests first and can run zero times; do-while tests last and runs at least once. Use while for waiting on a flag or consuming data until it is gone; use do-while when the action comes before the decision, such as a retry loop or converting the number 0 to text.

wdw_iq.c
#include <stdio.h> int main(void) { int n = 0, a = 0, b = 0; while (n > 0) a++; do { b++; } while (n > 0); printf(“while ran %d, do-while ran %d\n”, a, b); return 0; }
Output (verified by compiling and running)
while ran 0, do-while ran 1
Q2. How do you write a safe polling loop on a hardware flag?Intermediate+

Access the register through a volatile pointer (the CMSIS struct members are), loop on the flag test, and bound the loop with a timeout: uint32_t t = TIMEOUT; while (!(REG & FLAG)) { if (--t == 0) return ERR_TIMEOUT; }. When the elapsed time matters use the SysTick millisecond counter with unsigned subtraction. Report the failure and leave the hardware in a safe state.

Q3. Why can a while loop on a normal variable become an infinite loop under optimisation?Intermediate+

If the variable is not volatile and the loop body does not modify it, the compiler may assume it cannot change and read it only once, replacing while (!done) ; by an unconditional loop. A change made by an interrupt service routine or another core is invisible. Declare the variable volatile (and use atomic access if more than one word is involved).

Q4. What does while (*dst++ = *src++); do, and what is wrong with it?Intermediate+

It copies a string including the NUL: the assignment is the condition, and its value is the copied character, so the loop ends after copying the terminator. Problems: it performs no bounds check on the destination, the assignment in the condition triggers warnings, and the body is an empty statement that is easy to misread. Prefer strncpy-like bounded copies or an explicit length-checked loop.

strcpy_iq.c
#include <stdio.h> int main(void) { char dst[8]; const char *src = “ARM”; char *d = dst; const char *s = src; while ((*d++ = *s++) != ‘\0’) ; printf(“%s\n”, dst); return 0; }
Output (verified by compiling and running)
ARM
Q5. Explain the do { } while (0) macro idiom.Intermediate+

A macro that expands to several statements breaks when used as the body of an if without braces, or before an else. Wrapping them in do { ... } while (0) makes the whole expansion a single statement that expects the caller’s semicolon. The loop runs exactly once and the compiler removes the loop overhead.

Q6. Where does a while (1) super loop spend its time, and how do you save power?Intermediate+

It spins at full speed even when nothing has to be done. Add __WFI() (wait for interrupt) at the end of the loop body: the core sleeps until the next interrupt (SysTick, UART, timer), then handles flags and sleeps again. Select deeper sleep modes (Stop, Standby) via the PWR registers when the application permits.

Q7. How do you implement a delay of 10 ms without a timer interrupt?Intermediate+
delay_iq.c
#include <stdio.h> #include <stdint.h> static volatile uint32_t ms_ticks; /* SysTick increments this */ static void tick(void) { ms_ticks++; } static void delay_ms(uint32_t ms) { uint32_t start = ms_ticks; while ((uint32_t)(ms_ticks – start) < ms) /* unsigned subtraction survives wrap-around */ tick(); /* in the simulation we advance time here */ } int main(void) { uint32_t t0 = ms_ticks; delay_ms(10); printf(“waited %u ms\n”, (unsigned)(ms_ticks – t0)); return 0; }
Output (verified by compiling and running)
waited 10 ms

On the board the SysTick interrupt (configured with SysTick_Config(SystemCoreClock / 1000)) increments ms_ticks; the loop only compares. The comparison ms_ticks - start < ms keeps working when the 32-bit counter wraps after 49.7 days.

Q8. A while loop reading UART data sometimes misses bytes. What do you check?Advanced+

Polling at the wrong rate: if another task blocks for longer than one character time at the baud rate (87 µs at 115200 baud) the receive data register is overwritten (the overrun error flag ORE in USART_SR). Use the RXNE interrupt with a ring buffer, or DMA with idle-line detection. Also clear the error flags, which are cleared by reading SR then DR, otherwise reception can stall.

Q9. What is the worst-case execution time of a loop and why does it matter?Advanced+

It is the longest time the loop can take over all inputs, e.g. the maximum trip count times the cost of one pass. Real-time and safety-related software needs bounded loops so the deadline can be proved: timeouts, maximum retry counts and iteration limits on searches. A loop whose termination depends on external data without a bound can break the schedule.

Q10. How can the compiler optimise while (n--) loops on ARM Cortex-M?Advanced+

The decrement can set the condition flags directly (SUBS) and the loop branches back on not-zero (BNE) without a separate compare. GCC does this at -O1 and above for simple counting loops. In Thumb-2 there is no hardware loop instruction on the Cortex-M4 (Armv8.1-M adds low-overhead loops with DLS/LE on the Cortex-M55/M85).

Q11. Why is while (cond) { … } with the update at the top sometimes preferred over for?Advanced+

When the increment depends on data, such as parsing variable-length records where each iteration consumes a different number of bytes, a for header with a fixed step would be misleading. A while loop makes it explicit that the progress happens inside the body. MISRA, however, wants every such loop to have a provable bound.

Study Plan: Using Your Score on These While Loop Interview Questions

ScoreMeaningNext step
90–100%ExcellentContinue to Lesson 7.3: break, continue and nested loops.
70–89%GoodRedo Examples 1, 3 and 8 of this lesson.
Below 70%ReviseRe-read theory sections 1–6, then retake the quiz.
Habit to build: For every while loop ask: what makes the condition false? If you cannot answer, add a bound or a timeout.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

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