Skip to study material
← Question index

QUESTION 22 · Loops

Compare while, for and do-while loops.

5 marks

Answer in brief

The three loops all support repetition, but differ in where their condition is tested and how their control expressions are arranged.

While

The test appears before the body. Initialisation is normally written before the loop and the update inside the body. It is useful when a condition, rather than a simple fixed count, is the main reason for repeating. If its first condition is false, its body does not execute.

For

The header places initialisation, the condition and the update together. Initialisation runs once; then the condition is tested before every body execution. It is convenient for counter-controlled repetition. With continue, the update runs before the next condition test.

Do-while

The body appears before the condition. Therefore at least one execution occurs. It is useful for a menu that must be displayed before deciding whether to repeat. With continue, control moves to the ending condition test. A semicolon follows that test.

Example

Start i at 5 and use i <= 3 as the condition. A while loop and a for loop skip their bodies. A do-while loop executes its body once before discovering that the condition is false. The choice therefore affects program behaviour, not just appearance.

Choosing a loop

Use for for a clear counting task, while for a condition-controlled task, and do-while when the first action is compulsory. These are guidelines, not restrictions. Equivalent loops can have the same complexity. Count iterations and body work to determine time; changing the keyword alone does not improve an algorithm.

Comparison table

↔ Scroll horizontally on a small screen
Loop differences
Featurewhilefordo-while
Test positionBefore bodyBefore bodyAfter body
Minimum executions001
continue destinationConditionUpdate, then conditionCondition
Common useCondition-controlled workCountingAt least one action

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 →