C · Course navigation

C conditions, loops, and totals

Combine a counted loop with an even-number condition.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1#include <stdio.h>
2#include <assert.h>
3int 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading