One-dimensional arrays
Many sensor readings under one name: declaring and initializing an array, index and element, length and last index, walking the array with a loop, the off-by-one fault, reading input into an array, and walking backward, over a range and with a step.
Ten channels, ten variables?
A production test rig has ten ADC channels. Each channel gives one integer reading. The first version of the program used ten separate variables:
int r1, r2, r3, r4, r5;
int r6, r7, r8, r9, r10;
scanf("%d", &r1);
scanf("%d", &r2);
/* eight more copies */Ten copies of the same line. A technician copied one of them wrong, and channel 7 was never read. Nobody noticed, because every line looked almost the same.
An array (מערך) solves this. It is one name for many values of the same type, stored in order. A loop can then run the same line for every reading:
#define LENGTH 10
int readings[LENGTH];
for (int i = 0; i < LENGTH; i++) {
scanf("%d", &readings[i]);
}The loop changes the index, so one line reads every channel. For 100 channels you change one number.
Arrays appear everywhere in electronics: an ADC scan (10 channel readings), a sample buffer (100 voltage samples for an average, a minimum and a maximum), a lookup table (calibration values picked by index), an event log (recent fault codes to count or search). In every case: many values of one type that belong to one ordered collection.
Declaring an array
We will use the same five readings in the whole unit:
int readings[5] = {412, 398, 405, 421, 399};Read the declaration in four parts:
| Part | Meaning |
|---|---|
int | the type of every element |
readings | the name of the array |
[5] | the length: how many elements |
= {412, 398, 405, 421, 399} | the initial values, in order (the initializer, אתחול) |
Each value in the array is an element (איבר). Its position is its index (אינדקס). The first index is 0, not 1:
| index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| value | 412 | 398 | 405 | 421 | 399 |
If you give the values, you may leave the length out and the compiler counts them: int limits[] = {10, 20, 30}; has length 3.
One index selects one element
readings[2] means "the element at index 2 of readings". Here it is 405. You can read it, print it, or assign to it like any int variable:
printf("%d\n", readings[0]); /* prints 412, the first element */
printf("%d\n", readings[4]); /* prints 399, the last element */
readings[3] = 420; /* changes the fourth element */The index is the position. The element stores the value. Do not mix them up: the value at index 3 is 421, and the value 399 sits at index 4.
Length and last index are different
An array of length 5 has the indexes 0, 1, 2, 3, 4. The last valid index is 4, one less than the length. Index 5 is outside the array.
The rule for a valid index:
0 <= index && index < lengthC does not check this for you. Reading readings[5] compiles without an error, and then the program reads whatever happens to be in memory after the array. This is undefined behavior (התנהגות לא מוגדרת): the program may print nonsense, seem to work, or crash, and it may behave differently every time. Keeping every index inside the array is your job.
Walking the array with a loop
To visit every element, let a loop move the index from 0 to LENGTH - 1. This is called a traversal (מעבר על המערך):
#include <stdio.h>
#define LENGTH 5
int main(void)
{
int readings[LENGTH] = {412, 398, 405, 421, 399};
for (int i = 0; i < LENGTH; i++) {
printf("%d: %d\n", i, readings[i]);
}
return 0;
}0: 412
1: 398
2: 405
3: 421
4: 399In each iteration i is the position and readings[i] is the data at that position. When i is 2, readings[i] means readings[2], which is 405. After the last iteration i becomes 5, the test 5 < 5 is false, and the loop ends before index 5 is ever read.
Why this loop is safe:
istarts at 0, the first index.i < LENGTHstops before indexLENGTH.- Every valid index is visited exactly once.
- One constant,
LENGTH, controls both the size of the array and the loop. Change it in one place.
The off-by-one fault
The most common array bug is one character long:
for (int i = 0; i <= LENGTH; i++) { /* wrong: <= */
printf("%d\n", readings[i]);
}With <= the loop also runs for i == 5 and reads readings[5], outside the array.
Reading input into an array
scanf needs the address where it stores the value. For one element that is &readings[i]: readings[i] selects an int, and & gives its address.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define LENGTH 5
int main(void)
{
int readings[LENGTH];
for (int i = 0; i < LENGTH; i++) {
printf("Reading %d: ", i);
scanf("%d", &readings[i]);
}
printf("Stored:");
for (int i = 0; i < LENGTH; i++) {
printf(" %d", readings[i]);
}
printf("\n");
return 0;
}Reading 0: 412
Reading 1: 398
Reading 2: 405
Reading 3: 421
Reading 4: 399
Stored: 412 398 405 421 399The first loop fills indexes 0 to 4, one element per iteration. The second loop prints them.
Partial initialization
If the initializer has fewer values than the length, the rest are filled with zero:
int values[5] = {7, 9}; /* values is {7, 9, 0, 0, 0} */An array declared inside a function with no initializer at all holds unknown values, whatever was in that memory before:
int values[5]; /* five unknown values */Never read an element before you have given it a value, either with an initializer or with an assignment or input. Initialization is not the same as later input.
Forward, backward, a range and a step
A loop header has three parts: where to start, when to continue, and how to step. Choose them from the positions you need. Here is the same array of five values, forward and then backward:
#include <stdio.h>
#define LENGTH 5
int main(void)
{
int data[LENGTH] = {12, 18, 15, 21, 17};
printf("Forward: ");
for (int i = 0; i < LENGTH; i++) {
printf(" %d", data[i]);
}
printf("\n");
printf("Backward:");
for (int i = LENGTH - 1; i >= 0; i--) {
printf(" %d", data[i]);
}
printf("\n");
return 0;
}Forward: 12 18 15 21 17
Backward: 17 21 15 18 12Backward starts at LENGTH - 1, because index LENGTH is outside the array. The direction changes; the valid indexes do not.
The six traversal patterns you will use most:
| Pattern | Start | Continue while | Step | Used for |
|---|---|---|---|---|
| Every element | i = 0 | i < length | i++ | input, print, sum, count |
| Backward | i = length - 1 | i >= 0 | i-- | reverse order |
| Selected range | i = start | i <= end | i++ | part of the array |
| Fixed step | i = 0 | i < length | i += 2 | even indexes, sampled data |
| Adjacent pairs | i = 1 | i < length | i++ | compare with data[i - 1] |
| Until found | i = 0 | i < length | i++ | search, stop at a match |
A range from start to end (both included) visits end - start + 1 positions: from 2 to 6 that is five positions. Check 0 <= start <= end < length before the loop. A step of 2 from index 0 visits 0, 2, 4, 6, 8. Adjacent pairs and search come in the next lesson.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| array | מערך | many values of one type under one name, in order |
| element | איבר | one value stored in the array |
| index | אינדקס | the position of an element, starting at 0 |
| length | אורך המערך | the number of elements |
| initializer | אתחול | the values in braces: {412, 398, 405} |
| traversal | מעבר על המערך | visiting the elements with a loop |
| out of bounds | חריגה מגבולות המערך | an index outside 0 to length - 1 |
| off-by-one | טעות באחד | a loop that runs one time too many or too few, like i <= LENGTH |
| undefined behavior | התנהגות לא מוגדרת | C promises nothing about what happens |
Practice
More questions, with answers: Practice: arrays, questions 1 to 5, 11, 12, 14, 15 and 20, and Practice: traversal and strings, questions 35 to 38.