C PROGRAMMING · BEGINNER
C For Loop Visualization: Trace Each Iteration
Trace the initialization, condition, body and update of a C for loop. Use Next and Previous to see exactly which values print and when the loop terminates.
01 / UNDERSTAND
Start with working C code
The output is 1, 2 and 3 on separate lines. The value 4 is checked but never printed because the condition becomes false.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 3; ++i) {
printf("%d\n", i);
}
return 0;
}
02 / VISUALIZE
Interactive loop visualization
Use the controls to follow the C example above. The labels describe the current model state.
The explanatory material on this page is also available without JavaScript. Enable JavaScript to use the visual step controls.
Ready to explore the example.
AI Tutor — C for loops
The tutor uses the current step of this example. Responses are AI-generated and may contain mistakes. Check them against the interactive trace.
Limited free beta: AI requests are shared across visitors and may be unavailable when today's allowance is used. You can always use the interactive visualization without AI. Do not enter personal details, passwords or private information; questions are processed by Cloudflare Workers AI. Read how AI questions are handled before using the tutor.
This preview is not enabled for students. Paste the temporary tester key you generated on your own computer. Never paste your Turnstile Secret Key.
How does a C for loop work?
The syntax is for (initialization; condition; update). Initialization runs once. Before every iteration, C evaluates the condition. If it is true, the body executes and then the update runs. When the condition is false, execution continues after the loop.
- Initialize:
int i = 1. - Check:
i <= 3before executing the body. - Execute: print the current value of
i. - Update:
++iincrements the counter by one.
Common C loop mistakes
Off-by-one errors: i < 3 prints only 1 and 2; i <= 3 includes 3. Infinite loops: if the update never makes the condition false, the loop may not finish. Zero iterations: starting with i = 4 makes the initial condition false and prints nothing.
The model above deliberately separates checking the condition from printing a value. A continue statement in a for loop still proceeds to its update expression before the next condition check.
03 / PRACTICE
Try it yourself
- Predict the output if
i = 0andi <= 3. - Change the update to
i += 2. Which values appear? - Explain why
i = 4is evaluated but not printed in the original loop.
Check your predictions
The first example prints 0, 1, 2 and 3. The second prints 1 and 3. In the original loop, 4 makes the condition false before the body can execute.