Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Array Programming Exercises in C
Solve five core array tasks: highest plus lowest, even sum with odd product, descending sorts, reversing a prefix and rotating by any amount.
These array programs in C are the standard exercises that every beginner meets at the end of the arrays chapter, and they appear again in interviews for embedded roles. In this lecture of our free C programming course you will solve five of them with clear, original, tested code. Along the way you will see how embedded C programming shapes the solution: no recursion, fixed buffers, minimal extra memory and careful handling of empty or oversized input.
Topics Covered
What You Will Learn
- Finding the highest and lowest values in a single pass.
- Combining an even-number sum and an odd-number product, including the case with no odd numbers.
- Descending selection sort, bubble sort and insertion sort side by side.
- Reversing only the first n elements of an array safely.
- Rotating an array right by any number of positions using three reversals.
Prerequisites
- One-dimensional arrays and loops.
- Functions that receive an array and its length.
- The sorting ideas from the previous lectures in this chapter.
Why These Array Programs in C Matter
Each of these array programs in C trains a different skill. Finding extremes teaches correct initialisation. The even and odd task teaches classification with the remainder operator and shows how an innocent starting value can ruin a product. Sorting teaches comparison logic, and the reversal and rotation programs teach index arithmetic, which you will use constantly in buffers and drivers. Interviewers like these array programs in C because the code is short, yet small mistakes in boundaries or initial values are easy to spot. Write each solution yourself before reading ours, and test the edge cases listed later in this lecture.
Task 1: Sum of Highest and Lowest
Start both the highest and lowest at the first element, then scan the rest once. Starting at zero would be wrong because an array of all negative numbers would report a highest value of 0, which is not in the data. One pass is enough, so the time is O(n) and the extra memory is two integers.
Task 2: Even Sum and Odd Product
Use the remainder operator to classify each element: an even number gives remainder 0 when divided by 2. Add even numbers to a sum, and multiply odd numbers into a product that starts at 1. Starting the product at 1 is essential, since starting at 0 would force the answer to 0. If the array contains no odd numbers the product would still print 1, which is misleading, so keep a flag that tells you whether any odd number was found.
Task 3: Sort in Descending Order
You already know the three classic sorts in ascending order. To sort in descending order, change only the comparison. The table shows the single change in each algorithm.
| Sort | Idea | Descending change | Worst time | Extra memory |
|---|---|---|---|---|
| Selection | Pick the largest remaining and place it next | Choose the maximum, not the minimum | O(n²) | O(1) |
| Bubble | Swap neighbours that are out of order | Swap when left is smaller than right | O(n²) | O(1) |
| Insertion | Insert each item into the sorted left part | Shift while left items are smaller than the key | O(n²) | O(1) |
Bubble sort below stops early if a full pass makes no swap, which makes it fast on data that is already ordered. Insertion sort is usually the best of the three for small or nearly sorted arrays, which is why many embedded libraries use it for tiny inputs.
Task 4: Reverse the First n Elements
Two indexes walk toward each other: one from the front and one from position n minus 1. Swap and move until they meet. Validate n first. If n is 0 or 1 there is nothing to do, and if n is larger than the array length the function must refuse, otherwise it will write outside the array.
Task 5: Rotate Right by k Using Three Reversals
Rotating nine elements right by three should turn 1 to 9 into 7, 8, 9, 1, 2, 3, 4, 5, 6. You could shift elements one position at a time k times, but that costs O(n × k). A smarter way needs only reversals and no extra array: reverse the whole array, then reverse the first k elements, then reverse the remaining elements. First reduce k with the remainder operator, because rotating by the array length returns the original array.
| Stage | Array contents |
|---|---|
| Original | 1 2 3 4 5 6 7 8 9 |
| Reverse all | 9 8 7 6 5 4 3 2 1 |
| Reverse first 3 | 7 8 9 6 5 4 3 2 1 |
| Reverse last 6 | 7 8 9 1 2 3 4 5 6 |
Complete Program for Array Programs in C
All five tasks are in one file. The sorting functions work on copies so each starts from the same input.
#include <stdio.h>
#include <stddef.h>
static void print_array(const char *label, const int a[], size_t n)
{
printf("%s", label);
for (size_t i = 0; i < n; i++)
printf(" %d", a[i]);
putchar('\n');
}
static void copy_array(int dst[], const int src[], size_t n)
{
for (size_t i = 0; i < n; i++)
dst[i] = src[i];
}
static void reverse_range(int a[], size_t lo, size_t hi)
{
while (lo < hi) {
int tmp = a[lo];
a[lo] = a[hi];
a[hi] = tmp;
lo++;
hi--;
}
}
static void reverse_prefix(int a[], size_t len, size_t n)
{
if (n < 2 || n > len)
return;
reverse_range(a, 0, n - 1);
}
static void rotate_right(int a[], size_t len, size_t k)
{
if (len < 2)
return;
k %= len;
if (k == 0)
return;
reverse_range(a, 0, len - 1);
reverse_range(a, 0, k - 1);
reverse_range(a, k, len - 1);
}
static void selection_desc(int a[], size_t n)
{
for (size_t i = 0; i + 1 < n; i++) {
size_t big = i;
for (size_t j = i + 1; j < n; j++)
if (a[j] > a[big])
big = j;
if (big != i) {
int tmp = a[i];
a[i] = a[big];
a[big] = tmp;
}
}
}
static void bubble_desc(int a[], size_t n)
{
for (size_t pass = 0; pass + 1 < n; pass++) {
int swapped = 0;
for (size_t j = 0; j + 1 < n - pass; j++) {
if (a[j] < a[j + 1]) {
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
swapped = 1;
}
}
if (!swapped)
break;
}
}
static void insertion_desc(int a[], size_t n)
{
for (size_t i = 1; i < n; i++) {
int key = a[i];
size_t j = i;
while (j > 0 && a[j - 1] < key) {
a[j] = a[j - 1];
j--;
}
a[j] = key;
}
}
int main(void)
{
int readings[] = {42, 17, 93, 8, 56, 71};
size_t count = sizeof readings / sizeof readings[0];
/* Task 1: highest + lowest */
int hi = readings[0], lo = readings[0];
for (size_t i = 1; i < count; i++) {
if (readings[i] > hi) hi = readings[i];
if (readings[i] < lo) lo = readings[i];
}
printf("Task 1: highest = %d, lowest = %d, sum = %d\n", hi, lo, hi + lo);
/* Task 2: even sum and odd product */
int values[] = {3, 4, 7, 10, 5, 6, 9};
size_t vcount = sizeof values / sizeof values[0];
int even_sum = 0;
long odd_product = 1;
int found_odd = 0;
for (size_t i = 0; i < vcount; i++) {
if (values[i] % 2 == 0) {
even_sum += values[i];
} else {
odd_product *= values[i];
found_odd = 1;
}
}
printf("Task 2: even sum = %d, odd product = ", even_sum);
if (found_odd)
printf("%ld\n", odd_product);
else
printf("none\n");
/* Task 3: three descending sorts on copies */
int source[] = {29, 7, 41, 3, 18, 52, 11};
size_t scount = sizeof source / sizeof source[0];
int work[7];
copy_array(work, source, scount);
selection_desc(work, scount);
print_array("Task 3 selection:", work, scount);
copy_array(work, source, scount);
bubble_desc(work, scount);
print_array("Task 3 bubble: ", work, scount);
copy_array(work, source, scount);
insertion_desc(work, scount);
print_array("Task 3 insertion:", work, scount);
/* Task 4: reverse first n */
int seq[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
reverse_prefix(seq, 9, 4);
print_array("Task 4 reverse first 4:", seq, 9);
/* Task 5: rotate right */
int ring[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
rotate_right(ring, 9, 3);
print_array("Task 5 rotate by 3:", ring, 9);
int ring2[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
rotate_right(ring2, 9, 10);
print_array("Task 5 rotate by 10:", ring2, 9);
return 0;
}
gcc -std=c11 -Wall -Wextra -o array_tasks array_tasks.c
./array_tasks
Output:
Task 1: highest = 93, lowest = 8, sum = 101
Task 2: even sum = 20, odd product = 945
Task 3 selection: 52 41 29 18 11 7 3
Task 3 bubble: 52 41 29 18 11 7 3
Task 3 insertion: 52 41 29 18 11 7 3
Task 4 reverse first 4: 4 3 2 1 5 6 7 8 9
Task 5 rotate by 3: 7 8 9 1 2 3 4 5 6
Task 5 rotate by 10: 9 1 2 3 4 5 6 7 8
What the Output Shows
The highest value 93 and lowest value 8 give a sum of 101. The even numbers 4, 10 and 6 add to 20, and the odd numbers 3, 7, 5 and 9 multiply to 945. All three sorts finish with the same descending order, which is a good self-check. Rotating by 10 on a nine-element array behaves exactly like rotating by 1, because 10 modulo 9 is 1.
Real-World Embedded C Uses
- Min and max tracking: sensor firmware often records the extremes of a sampling window in one pass without storing every sample.
- Circular buffers: rotation logic is the idea behind ring buffers used for UART and ADC data.
- Sorting small sets: picking the median of five readings for noise filtering uses a tiny insertion sort.
- Reversal: byte-order and bit-order conversions are reversals of small arrays.
Common Mistakes and Troubleshooting
| Mistake | Effect | Fix |
|---|---|---|
| Initialising highest to 0 | Wrong answer for all-negative data | Start at the first element |
| Initialising the odd product to 0 | Always 0 | Start at 1 and track whether any odd was found |
| Using int for the product | Overflow with many odd numbers | Use a wider type and check ranges |
Unsigned loop with j >= 0 | Infinite loop | Count with j > 0 and subtract inside the body |
| Rotating without reducing k | Index out of range or wasted work | Use k %= len first |
| No length check in reverse_prefix | Writes outside the array | Reject n greater than len |
Best Practices, Performance and Security
- Choose insertion sort for tiny arrays and a library or a better algorithm when n grows, since all three simple sorts are O(n²).
- The three-reversal rotation is O(n) time and O(1) memory, which suits microcontrollers.
- Be careful with
size_t: it is unsigned, so expressions such asn - 1wrap around when n is 0. The functions above guard against this. - Validate every length and index that comes from outside the program, such as a packet field.
- Write a small test for edge cases: empty array, one element, all equal values and negative numbers.
Summary
- Initialise extremes from real data, and initialise products at 1.
- Descending sorts differ from ascending sorts only in the comparison.
- Reverse a prefix with two moving indexes after validating the length.
- Rotate by reversing the whole array, then the two parts.
- Always test with empty, single and repeated values.
Keep your own notebook of array programs in C with the edge cases that broke your first attempt, since those notes become your personal checklist before every exam or interview. With these array programs in C mastered, you are ready for the final lecture of the chapter: matrix programs, a chapter quiz and interview questions.
FAQ: Array Programs in C
How do I find the highest and lowest values in one pass?
Set both to the first element, then compare each remaining element against them and update whichever it beats.
Which sort is best for small arrays in embedded code?
Insertion sort is usually the simplest and quickest for small or nearly sorted data, and it needs no extra memory.
How do I sort in descending order?
Reverse the comparison: pick the maximum in selection sort, swap when left is smaller in bubble sort, and shift while earlier items are smaller in insertion sort.
How can I rotate an array without a second array?
Reverse the whole array, then reverse the first k elements, then reverse the rest. It uses constant extra memory.
Why use size_t for array lengths?
It is the type designed for sizes and matches the result of sizeof, but remember that it is unsigned and wraps below zero.
Keep Going With the Free C Programming Course
Every lecture in this free C tutorial for embedded systems is original, tested and written for beginners who want real embedded C programming skills. Move on to the next lecture or return to the course index.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments