Arrays and vectors in C: solved exercises step by step
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.
Problem statement
Build a program that:
- reads and validates the vector size,
- reads all elements from input,
- computes the total sum,
- finds the maximum value,
- counts how many elements are greater than a given threshold.
C solution
#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;
}Expected output
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: 2Common mistakes
- Not validating input size and causing out-of-bounds access.
- Using
i <= ninstead ofi < n. - Initializing max incorrectly (for example using
0with negative values). - Mixing input and processing in one hard-to-debug block.
Practical use
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.
Recommended next exercise
- For loop in C: solved exercises with accumulators and counters
- Matrices in C: solved exercises
- Binary search in C: solved exercise on sorted arrays
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
What is the difference between a vector and an array in C?
In C practice, both terms are often used for contiguous elements of the same type stored in memory.
How do I avoid index out-of-range bugs?
Validate size, use i < n consistently, and cap input with a fixed maximum like MAX_SIZE.
What should I practice after these exercises?
Move to sorting and search problems on arrays, then continue with matrices and file processing.