Skip to study material
← Question index

QUESTION 20 · Loops

Explain the do-while loop and show why it executes at least once.

5 marks

Answer in brief

The do-while loop executes its body first and tests its condition afterwards. It is an exit-controlled loop.

Syntax

do {
    /* loop body */
} while (condition);

Working

  1. Enter the loop and execute the body.
  2. Test the condition after the body.
  3. Repeat the body when the condition is non-zero; otherwise continue after the loop.

Example trace

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.

Uses

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.

Important points and complexity

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.

Flowchart

Control flow for do-while with labelled true and false paths.
Explain the do-while loop and show why it executes at least once. · Download diagram

C program and output

/* 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;
}

Sample input and output

This example uses values already written in the program.

Output

5

Related exam questions

Related questions in the loops category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q6(b) · 8 marks

    How is an entry-controlled loop different from an exit-controlled loop? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q2(b) · 5 marks

    Devise an algorithm for the sum of n numbers using while and for loops.

    Paper P02 · page 1

View this category in the exam question bank →