Skip to study material
← Question index

QUESTION 18 · Loops

Explain the for loop with syntax and its execution order.

5 marks

Answer in brief

The for loop places initialisation, a condition and an update in one header. It is often convenient when a counter controls repetition.

Syntax

for (initialisation; condition; update) {
    /* loop body */
}

Execution order

  1. Perform initialisation once.
  2. Test the condition. A zero result leaves the loop.
  3. Execute the body when the condition is true.
  4. Perform the update and test the condition again.

Example trace

In for (int i = 1; i <= 3; ++i), i starts at 1. The body prints 1, then the update makes i equal to 2. The next iterations print 2 and 3. When i becomes 4, the condition fails. The variable declared in this loop header is available within the loop, not after its scope ends.

Important points

Any of the three header expressions can be omitted. An omitted condition acts as true, so for (;;) repeats until control leaves it. A continue in a for body goes to the update and then the condition. A break leaves the loop without performing another update. Avoid changing the counter unexpectedly inside the body.

Complexity

When the counter runs from 1 through n and each body execution does constant work, there are n iterations, giving O(n) time. The loop stores only its counter, so auxiliary space is O(1). A for keyword alone does not determine complexity; the number of iterations and the body work do.

Flowchart

Control flow for for with labelled true and false paths.
Explain the for loop with syntax and its execution order. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    for (int i = 1; i <= 3; ++i) {
        printf("%d\n", 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 →