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:
- compute the sum
1..n, - count how many even numbers are in an array,
- find the maximum value in an array,
- compute the average of an array.
C solution
#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
sum_1_n(10) = 55
even_in_array = 3
max_array = 9
avg_array = 5.17Common mistakes
- Wrong loop range (
i <= nversusi < 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.
Recommended next exercise
- While and do while in C: solved exercises
- Arrays and vectors in C: solved exercises
- Insertion sort in C: solved exercise
- All C exercises
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.