Arrays and vectors in C: solved beginner exercises

  3 minutes

If you are looking for vector exercises in C, this guide gives practical training around the most common beginner tasks in classes and technical screenings.

You will practice safe input, cumulative sum, maximum search, and conditional counting.

Build a program that:

  1. reads and validates the vector size,
  2. reads all elements from input,
  3. computes the total sum,
  4. finds the maximum value,
  5. counts how many elements are greater than a given threshold.
#include <stdio.h>

#define MAX_SIZE 100

int read_size(void) {
    int n;
    do {
        printf("Enter vector size (1..%d): ", MAX_SIZE);
        scanf("%d", &n);
    } while (n < 1 || n > MAX_SIZE);
    return n;
}

void read_vector(int v[], int n) {
    for (int i = 0; i < n; i++) {
        printf("v[%d] = ", i);
        scanf("%d", &v[i]);
    }
}

int sum_vector(const int v[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += v[i];
    }
    return sum;
}

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

int count_greater_than(const int v[], int n, int threshold) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (v[i] > threshold) {
            count++;
        }
    }
    return count;
}

int main(void) {
    int v[MAX_SIZE];
    int n = read_size();

    read_vector(v, n);

    int sum = sum_vector(v, n);
    int max_value = max_vector(v, n);
    int threshold = 10;
    int greater = count_greater_than(v, n, threshold);

    printf("\nTotal sum: %d\n", sum);
    printf("Maximum: %d\n", max_value);
    printf("Greater than %d: %d\n", threshold, greater);

    return 0;
}
Enter vector size (1..100): 5
v[0] = 4
v[1] = 12
v[2] = 7
v[3] = 20
v[4] = 10

Total sum: 53
Maximum: 20
Greater than 10: 2
  • Not validating input size and causing out-of-bounds access.
  • Using i <= n instead of i < n.
  • Initializing max incorrectly (for example using 0 with negative values).
  • Mixing input and processing in one hard-to-debug block.

These array exercises in C are useful for:

  • simple statistics over data lists,
  • condition-based filters,
  • fundamentals required for sorting, searching, and matrix work.

They are a practical bridge from basic syntax to real problem solving.

If you want a complete path with progressive difficulty:

In C practice, both terms are often used for contiguous elements of the same type stored in memory.

Validate size, use i < n consistently, and cap input with a fixed maximum like MAX_SIZE.

Move to sorting and search problems on arrays, then continue with matrices and file processing.