🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Loop Through Arrays in C
Chapter 7, Lecture 4 of the free C programming course: the for-loop pattern that reads, prints and analyses every element, with two complete sensor-style programs.
An array on its own is just storage. Its real power appears when you loop through arrays in C and process every element with a few lines of code. Averaging samples, finding a peak, counting alarms: all of these are the same loop wearing different clothes. This lecture belongs to our free C programming course and free embedded C course, and the examples mirror what C programming for embedded systems engineers write every day when they turn raw sensor readings into decisions.
What You Will Learn
- The standard for-loop pattern for walking an array from the first element to the last
- How to fill an array from user input and validate each entry
- How to print an array and total its elements
- How to compute average, maximum, minimum and threshold counts in a single pass
- How to classify elements as even or odd while looping
- How to avoid integer-division and off-by-one traps
Prerequisites
- Lectures 1 to 3 of this chapter
- The
forloop, theifstatement and the modulus operator% - The
scanf()function and its return value
The Loop Pattern for Arrays in C
Because indices run from 0 to size minus 1, one loop shape handles almost every array job:
for (i = 0; i < SIZE; i++) {
/* work with arr[i] */
}
The counter starts at 0, the test i < SIZE stops the loop one step before the invalid index, and i++ moves to the next element. The body runs exactly SIZE times, once per element. That is the whole trick.
The Four Everyday Array Tasks
| Task | Loop body idea | Needs a helper variable? |
|---|---|---|
| Read values in | scanf(“%d”, &arr[i]); | No |
| Display values | printf(“%d “, arr[i]); | No |
| Add all elements | sum += arr[i]; | Yes, sum starting at 0 |
| Find the largest | if (arr[i] > max) max = arr[i]; | Yes, max starting at arr[0] |
Reading an Array from the Keyboard
The first program logs six temperature readings. Notice that it checks the return value of scanf(): the function returns how many values it converted, so anything other than 1 means the user typed something that is not an integer. Ignoring that return value is how programs end up with garbage in their arrays.
#include <stdio.h>
#define COUNT 6
int main(void)
{
int temp[COUNT];
int i;
for (i = 0; i < COUNT; i++) {
printf("Enter temperature %d: ", i);
if (scanf("%d", &temp[i]) != 1) {
printf("\nBad input, stopping.\n");
return 1;
}
}
printf("\nLogged values:");
for (i = 0; i < COUNT; i++) {
printf(" %d", temp[i]);
}
printf("\n");
return 0;
}
gcc -Wall -Wextra -std=c11 -o temp_log temp_log.c
./temp_log
A sample session, with the numbers you type shown after each prompt:
Enter temperature 0: 21
Enter temperature 1: 25
Enter temperature 2: 19
Enter temperature 3: 30
Enter temperature 4: 28
Enter temperature 5: 23
Logged values: 21 25 19 30 28 23
Two loops, two jobs: the first fills the array, the second prints it. Keeping input and output in separate loops makes each loop trivial to read and to test. Typing a word such as abc at any prompt triggers the Bad input message and ends the program with a non-zero exit code.
Analysing an Array in a Single Pass
Real firmware rarely needs just one statistic. A single loop can compute several at once, which is also faster than looping repeatedly. The next program holds eight temperature readings and reports the sum, the average, the maximum, the minimum, how many readings exceed a limit, and how many are even or odd. The even and odd counts are not a realistic sensor metric, but they exercise the modulus operator inside an array loop, which is a very common exam and interview pattern.
#include <stdio.h>
#define N 8
int main(void)
{
int data[N] = {27, 31, 24, 38, 29, 35, 22, 30};
int i, sum = 0, max, min, above = 0, even = 0, odd = 0;
const int limit = 30;
float avg;
max = min = data[0];
for (i = 0; i < N; i++) {
sum += data[i];
if (data[i] > max) max = data[i];
if (data[i] < min) min = data[i];
if (data[i] > limit) above++;
if (data[i] % 2 == 0) even++; else odd++;
}
avg = (float)sum / N;
printf("sum = %d\n", sum);
printf("average = %.2f\n", avg);
printf("max = %d\nmin = %d\n", max, min);
printf("above %d: %d readings\n", limit, above);
printf("even = %d, odd = %d\n", even, odd);
return 0;
}
gcc -Wall -Wextra -std=c11 -o array_stats array_stats.c
./array_stats
sum = 236
average = 29.50
max = 38
min = 22
above 30: 3 readings
even = 4, odd = 4
Tracing the Running Sum
If a loop surprises you, trace it on paper. The table below follows the sum and the running maximum across the eight iterations.
| i | data[i] | sum after step | max after step |
|---|---|---|---|
| 0 | 27 | 27 | 27 |
| 1 | 31 | 58 | 31 |
| 2 | 24 | 82 | 31 |
| 3 | 38 | 120 | 38 |
| 4 | 29 | 149 | 38 |
| 5 | 35 | 184 | 38 |
| 6 | 22 | 206 | 38 |
| 7 | 30 | 236 | 38 |
Why the Program Is Written This Way
- sum starts at 0. An accumulator that begins with garbage gives garbage totals.
- max and min start at data[0]. Starting max at 0 would fail for all-negative data; starting from the first real element is always correct.
- (float)sum / N. Dividing two integers throws away the fraction, so 236 / 8 would give 29. Casting one operand to
floatfirst keeps the .50. - %.2f prints two decimal places so the average looks tidy.
- One loop, five results. Every statistic is updated while the element is already in hand.
Loop Through Arrays in C: Real-World Use Cases
| Embedded scenario | Loop job |
|---|---|
| Smoothing a noisy analogue input | Sum the last N samples, divide by N |
| Over-temperature alarm | Count how many readings exceed a limit |
| Peak detection in vibration data | Track the running maximum |
| Checksum of a received packet | Add or XOR every byte of the buffer |
| Clearing a buffer after use | Assign 0 to each element in turn |
Performance Considerations
A loop over N elements takes time proportional to N. On a fast desktop that is invisible, but on a 16 MHz microcontroller that must also service an interrupt every millisecond, a 1000-element loop run too often can eat the entire time budget. Do the heavy loop only when needed, keep the loop body short, and avoid calling slow functions such as printf() inside it on a real device. Combining several statistics into one pass, as the program above does, is a simple and effective optimisation.
Common Mistakes When You Loop Through Arrays in C
Loop limit errors cause the nastiest array bugs. Writing i <= N makes the last pass use data[N], one element beyond the array. Always check the exact comparison when a loop touches memory.
- Forgetting to initialise the sum, count or maximum before the loop
- Dividing two integers when you expect a fractional average
- Forgetting the
&inscanf("%d", &arr[i]), which leads to a crash - Reusing the same loop counter inside a nested loop and breaking both loops
- Printing with
%dforfloatelements; the specifier must match the type
A Safety Checklist Before You Loop
Before you loop through arrays in C on real hardware, run through five quick questions. They take thirty seconds and prevent the most expensive bugs.
- Is the loop limit the same named constant used in the declaration?
- Does the last pass use index size minus 1, and never the size itself?
- Is every accumulator, counter and extreme value initialised before the first pass?
- Does the loop body avoid slow calls if it runs inside an interrupt handler or a timing-critical task?
- Have you tested the loop with the smallest and largest realistic data, including identical values?
The same checklist applies to every loop you will write later, whether it walks a short sensor window or a long communication buffer. It also explains why interviewers like array-loop questions: a candidate who runs this checklist out loud is clearly someone who has debugged real firmware.
Best Practices to Loop Through Arrays in C
- Use one constant for the size in the declaration and in every loop condition
- Check the return value of
scanf()before trusting the entry - Initialise accumulators and extremes explicitly, with a comment when the choice is subtle
- Keep one loop to one clear purpose unless you are deliberately merging passes for speed
- Test with edge data: an array of identical values, all negatives, a single large spike
Summary and Key Takeaways
Key takeaways
- Loop through arrays in C with
for (i = 0; i < SIZE; i++) - The same loop shape reads, prints, sums, searches and classifies elements
- Accumulators must be initialised; maximum and minimum should start from the first element
- Cast to
floatbefore dividing when you want a fractional average - One careful pass can produce several results at once, which is the efficient way to loop through arrays in C on small devices
Frequently Asked Questions
How do I loop through an array in C?
Use a for loop that starts the counter at 0 and continues while it is less than the array size, then use the counter as the subscript.
Why should the loop condition be i < SIZE and not i <= SIZE?
The last valid index is SIZE minus 1. Using <= makes the final pass access an element that does not exist.
How do I find the largest value in an array?
Set the maximum to the first element, then loop through the array and replace it whenever an element is larger.
Why does my average come out without decimals?
An integer divided by an integer gives an integer. Cast the sum to float before dividing, as in (float)sum / N.
How can I count even and odd numbers in an array?
Test each element with % 2 == 0 inside the loop and increase one of two counters.
Can I read a whole array with one scanf?
Not directly for numbers. You read the elements one at a time inside a loop, passing the address of each element.
Are array loops slow on microcontrollers?
The loop is fast, but the cost grows with the element count. Keep loops short in interrupt handlers and avoid slow calls such as printf() inside them.
Finish the Chapter with a Quiz
The next and final lecture of this chapter tests everything with output-prediction questions, programming challenges and embedded C interview questions, all part of our free C programming course.

2 Comments