Lesson 41: Check digit
One extra digit
- People make mistakes when they type a code: one wrong digit, or two digits swapped.
- A check digit is an extra digit at the end, worked out from the other digits.
- The computer works it out again. If the answer is different, the code was typed wrong. Barcodes and book numbers (ISBN) use one.
Words for this lesson
| Word | Meaning |
|---|---|
| check digit | an extra digit worked out from the others |
| weight | the number each digit is multiplied by |
| transposition | two digits swapped: 61 typed as 16 |
| % 10 | the last digit of a number (the remainder after ÷ 10) |
Work it out: 3216
| Digit | 3 | 2 | 1 | 6 |
|---|---|---|---|---|
| × weight | 1 | 2 | 3 | 4 |
| = | 3 | 4 | 3 | 24 |
- Total 34, last digit 4: the code with its check digit is 32164.
A character is a number
void setup() {
Serial.begin(9600);
String code = "3216";
int digit = code[3] - '0';
Serial.println(digit * 4);
}
void loop() {
}
- The Monitor shows 24:
code[3]is the character '6', and taking away '0' gives the number 6.
In the exam
- 0478/22/M/J/23 Q7: an algorithm calculates a check digit for a four-digit number: it adds each digit times its position (1 to 4) and the check digit is the total MOD 10, as in your first program. (a) Find the lines for totalling, a count-controlled loop and a post-condition loop. (b) The mark scheme's three errors: the total must use the array element (Number[Counter] times Counter, not Number), the stop test must look for −1, and the output loop must start at 1, not 0. (c) Add a check that each input is a single digit (0 to 9, a whole number) straight after the input.
- A check digit finds one wrong digit and two swapped digits, because each place has a different weight.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Type a 4-digit code into the Serial Monitor, for example 3216. Multiply each digit by its place (1st × 1, 2nd × 2, 3rd × 3, 4th × 4) and add them up: 3 + 4 + 3 + 24 = 34. The check digit is the last digit of the total: total % 10, here 4. Print Code: , the 4 digits and the check digit, for example Code: 32164.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Now check a code with its check digit, for example 32164. Work out the check digit again from the first 4 digits. If it is the same as the 5th digit, print the code and : valid; if not, print the code and : error. A swapped pair of digits (32614) must give an error too.
Nhấn Chạy để xem kết quả ở đây.