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
Perform initialisation once.
Test the condition. A zero result leaves the loop.
Execute the body when the condition is true.
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
Explain the for loop with syntax and its execution order. · Download diagram