QUESTION 19 · Loops
Why does a do-while loop execute its body at least once?
2 marksAnswer
It executes the body before testing the condition.
- The condition is checked at the end of each iteration.
- A semicolon is required after while (condition).
QUESTION 19 · Loops
It executes the body before testing the condition.
QUESTION 20 · Loops
The do-while loop executes its body first and tests its condition afterwards. It is an exit-controlled loop.
do {
/* loop body */
} while (condition);The example starts with i = 5. The body prints 5 and increments i to 6. Only then is i <= 3 tested. It is false, so the loop stops. This produces one output line even though the starting value would fail an equivalent while loop test.
do-while is useful when an action must happen before a repeat decision, such as displaying a menu and then checking whether the user requested another operation. It does not automatically validate input: the body must still check whether reading a value succeeded and whether the value is allowed.
The final semicolon is part of the syntax. A continue goes to the condition test, not directly to the beginning of the body. A break leaves the loop immediately. If the body performs constant work for n iterations, time is O(n), with at least one execution. A fixed number of variables gives O(1) auxiliary space. The sample deliberately demonstrates a single iteration.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int i = 5;
do {
printf("%d\n", i);
++i;
} while (i <= 3);
return 0;
}This example uses values already written in the program.
5Related questions in the loops category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
How is an entry-controlled loop different from an exit-controlled loop? Explain.
Paper P01 · page 1Devise an algorithm for the sum of n numbers using while and for loops.
Paper P02 · page 1