Lesson 48: Card reader
Is this card allowed?
- Many doors open with a card. The reader gets the card's ID number and looks for it in a list of allowed IDs.
- The list is an array. To find an ID, the program looks at each item in turn: a linear search.
- Arrays have a fixed size, so before adding a new card the program must check that there is room.
Words for this lesson
| Word | Meaning |
|---|---|
| array | many values under one name, by index |
| linear search | check each item, one after another |
| found | a flag: true once the item is seen |
| SIZE | how many items the array can hold |
Search 4096 in {1042, 2817, 3355, 4096}
| i | allowed[i] | Same as 4096? | found |
|---|---|---|---|
| 0 | 1042 | no | false |
| 1 | 2817 | no | false |
| 2 | 3355 | no | false |
| 3 | 4096 | yes | true |
- The last item matters: a loop that stops at i = 2 never finds 4096.
In the exam
- 0478/22/F/M/24 Q3(a): input a number and use a linear search on the array
Values[1:50]; output its position, or "Not found". The mark scheme's plan is the one in your first program: set a flag or a position before the loop, compare each item inside the loop, decide and output after the loop. - 0478/22/F/M/25 Q1: the standard method used to find a piece of data in an array is a linear search.
Dificultad 4/5 · 280 monedas + un pequeño bono en el primer intento de hoy
A door has a card reader. The IDs of the cards that may open it are in the array allowed. Type a card ID into the Serial Monitor. Use a búsqueda lineal: look at each item of the array in turn. If the ID is there, print Open: and the ID and light the green LED (pin 12); if not, print Closed: and the ID and light the red LED (pin 13).
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 5/5 · 400 monedas + un pequeño bono en el primer intento de hoy
The array has room for 6 cards, and count says how many are stored. Type ADD and an ID to add a card: if there is room, store it at allowed[count], add 1 to count and print Added: and the ID; if the array is full, print Full. Typing only an ID checks it as before.
Haz clic en Ejecutar para ver la salida aquí.