C conditions, loops, and totals
Combine a counted loop with an even-number condition.
C
#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;
}Output
12
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
#include <stdio.h>2
#include <assert.h>3
int main(void) {4
int total = 0;5
for (int i = 1; i <= 6; i++) {6
if (i % 2 == 0) total += i;7
}8
printf("%d\n", total);9
assert(total == 12);10
return 0;11
}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 |
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.