For loop in C: solved exercises with accumulators and counters

  3 minutes

If you searched for for loop in C solved exercises, this post gives practical patterns that appear in beginner classes and early interview screens.

The main goal is to master three key loop patterns: accumulation, counting, and array traversal.

Solve these 4 mini exercises with for:

  1. compute the sum 1..n,
  2. count how many even numbers are in an array,
  3. find the maximum value in an array,
  4. compute the average of an array.
#include <stdio.h>

int sum_1_n(int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

int count_even(const int a[], int n) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (a[i] % 2 == 0) {
            count++;
        }
    }
    return count;
}

int max_array(const int a[], int n) {
    int max_value = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] > max_value) {
            max_value = a[i];
        }
    }
    return max_value;
}

double avg_array(const int a[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
    return (double)sum / n;
}

int main(void) {
    int n = 10;
    int data[] = {7, 2, 9, 4, 6, 3};
    int len = (int)(sizeof(data) / sizeof(data[0]));

    printf("sum_1_n(%d) = %d\n", n, sum_1_n(n));
    printf("even_in_array = %d\n", count_even(data, len));
    printf("max_array = %d\n", max_array(data, len));
    printf("avg_array = %.2f\n", avg_array(data, len));

    return 0;
}
sum_1_n(10) = 55
even_in_array = 3
max_array = 9
avg_array = 5.17
  • Wrong loop range (i <= n versus i < n).
  • Not initializing accumulators or counters to zero.
  • Using integer division while computing averages.
  • Going out of bounds in arrays.

These for patterns appear in almost every early C exercise:

  • list processing,
  • basic statistics,
  • filtering by conditions.

Once these patterns are stable, arrays, sorting, and matrix exercises become easier.

If you want a complete path with progressive difficulty:

Neither is universally better, but for is usually clearer when the number of iterations is known.

An accumulator combines values (for example sum += a[i]). A counter tracks occurrences (count++).

Start with single-variable loops, then move to arrays, and finally combine multiple conditions inside one loop.