Skip to study material
← Question index

QUESTION 16 · Loops

Explain the while loop with syntax and an example.

5 marks

Answer in brief

The while loop repeats a body while its condition is true. It is an entry-controlled loop because the test comes before the body.

Syntax

while (condition) {
    /* repeated statements */
}

Working

  1. Set the initial values before the loop.
  2. Test the condition. If false, leave the loop.
  3. Execute the body when true, then return to the condition.

Example trace

The example starts with i = 1. The test i <= 3 succeeds, so 1 is printed and i becomes 2. The next iterations print 2 and 3. After the third update, i becomes 4. The condition is now false and the loop ends. The update is essential: without it, this example would continue printing 1.

Uses and important points

while is useful when repetition is controlled mainly by a condition, such as reading values until a sentinel is entered. The body can execute zero times. Use braces for multiple statements. An accidental semicolon after the condition creates an empty body. When continue is used, make sure an essential update is not skipped.

Complexity

A loop that performs constant work once for each of n values takes O(n) time. This example prints exactly three values, so the displayed run has fixed work. Generalising its limit to n gives O(n) time and O(1) auxiliary space because only a counter is needed.

Flowchart

Control flow for while with labelled true and false paths.
Explain the while loop with syntax and an example. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int i = 1;
    while (i <= 3) {
        printf("%d\n", i);
        ++i;
    }
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

1
2
3

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 →