C conditions, loops, and totals
Combine a counted loop with an even-number condition.
On this page
int variables and printf.
- Combine a counted loop with an even-number condition.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A for loop has initialization, a condition checked before each iteration, and an update after the body. The remainder operator identifies even integers.
The loop uses <= so its endpoint is included. Only values divisible by two are added to the accumulator.
Code example
#include <stdio.h>
#include <assert.h>
int main(void) {
int total = 0;
for (int i = 1; i <= 6; i++) {
if (i % 2 == 0) total += i;
}
printf("%d\n", total);
assert(total == 12);
return 0;
}12
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#include <stdio.h>#include <assert.h>int main(void) { int total = 0; for (int i = 1; i <= 6; i++) { if (i % 2 == 0) total += i; } printf("%d\n", total); assert(total == 12); return 0;}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Initialize before the loop. | total = 0 | — | |
| i=1 is skipped; i=2 is added. | total = 2 | — | |
| i=3 is skipped; i=4 is added. | total = 6 | — | |
| i=5 is skipped; i=6 is added. | total = 12 | — | |
| The loop ends at i=7; print the sum. | total = 12 | 12 |
Behind the scenes
How C processes this code
The C compiler produces a native program. Variables occupy memory, and execution enters main.
Cost and common mistakes
O(n) time up to endpoint n and O(1) auxiliary space.
- Signed integer overflow is undefined behavior in C; keep values within range.
- A stray semicolon after for would create an empty loop body.
Try it yourself
Change the endpoint to 8.
Reveal answer and reasoning
The total becomes 20 because 8 is included.