- Asked 2/16
- 2074 Asoj · 2 marks
- 2071 Shrawan · 3 marks
do...while versus for/while loops
Short answer
do...while is exit‑controlled, so its body runs at least once; for loop is entry‑controlled with initialisation, condition, and update in one header, typically used when the iteration count is known. do alone is just the keyword; the full construct is do { ... } while (condition).
Differentiate between do...while and for statements. Write the difference between do and do...while loop.
do...while versus for
| do...while | for |
|---|---|
| Exit-controlled: condition is tested after the body | Entry-controlled: condition is tested before the body |
| Body executes at least once | Body may not execute at all |
| Initialisation and update are written separately | Initialisation, condition and update are in one line |
Semicolon is needed after while(condition); | No semicolon after the header |
| Used when the number of repetitions is not known and at least one run is needed (menus) | Used when the number of repetitions is known |
do versus do...while
do is only the keyword that starts the loop; it cannot be used alone. The complete loop is do { ... } while (condition);, where do starts the body and the while clause at the end decides whether to repeat. The (entry-controlled) while loop tests first; the do...while loop tests after the body.
#include <stdio.h>
int main(void)
{
int i = 10;
while (i < 5)
printf("while body runs: %d\n", i);
do
{
printf("do-while body runs once: %d\n", i);
} while (i < 5);
for (i = 1; i <= 3; i++)
printf("for: %d\n", i);
return 0;
}
Output:
do-while body runs once: 10
for: 1
for: 2
for: 3
The while loop did not run (10 < 5 is false), but do...while ran once.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- While loop with syntax and flowchart · Computer Programming, chapter 5
- Syntax of while loop · Computer Programming, chapter 5
- DO versus implied DO loop · Computer Programming, chapter 11 · asked 3×
- Arithmetic versus logical IF · Computer Programming, chapter 11 · asked 3×
- Open loop versus closed loop control · Embedded System, chapter 7 · asked 6×
- Potential difference versus emf · Basic Electrical Engineering, chapter 1
- Subscriber loop and cable hierarchy · Telecommunications, chapter 1
- P-f and Q-V control loops · Power Plant Equipment, chapter 2 · asked 3×