For loop in C: solved exercises with accumulators and counters

For loop in C: solved exercises step by step

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.

Problem statement

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.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#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;
}

Expected output

1
2
3
4
sum_1_n(10) = 55
even_in_array = 3
max_array = 9
avg_array = 5.17

Common mistakes

  • 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.

Practical use

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.

Guided practice and next step

If you want a complete path with progressive difficulty:

FAQ

Is for better than while for beginners?

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

What is the difference between an accumulator and a counter?

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

How can I improve loop skills faster?

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