12 digit product codes: Calculate the last digit (one line of input)

Challenge Level: Ready to expand

Learning outcomes

Students will be able to:


Write a program that asks the user to enter the first 11 digits of a product code, in one line of input, and works out the last digit as the output. For this challenge make sure the user can only enter a 12 digit product code (the first 11 digits).

Testing examples:

Your program should display the outputs shown in this table for the given inputs provided:

Input Output
83831002252 The last digit is: 4
81157101357 The last digit is: 9
61414100001 The last digit is: 2
69277101744 The last digit is: 0



What it should look like

Click on the green flag, enter the inputs provided in the “testing examples” to see the expected output of your program.

Recommended blocks
when green flag clicked

ask [Enter first 11 digits of the product code:] and wait
say (join [The last digit of the product code is: ] (last digit))

say [You must enter a 11 digit number!]
repeat (5)

if <(length of (first 11 digits)) = [11]> then
set [index v] to [1]

set [first 11 digits v] to [0]

set [total 1 v] to [0]

set [total 2 v] to [0]

set [last digit v] to [0]

set [total 1 v] to ((total 1) + (letter (index) of (first 11 digits)))

change [index v] by (1)

set [last digit v] to (((0) - (((total 1) * (3)) + (total 2))) mod (10))

set [total 1 v] to ((total 1) + (letter (index) of (first 11 digits)))

change [index v] by (1)

set [total 2 v] to ((total 2) + (letter (index) of (first 11 digits)))

change [index v] by (1)

set [first 11 digits v] to (answer)
  • For the 11 digits entered, you need to add up 1st, 3rd, 5th and so on digits and store the result in a variable called total 1. Then add up 2nd, 4th, 6th and so on digits and store the result in variable called total 2. The last digit (check digit) is then calculated by subtracting the sum of total 1 multiplied by 3 and total 2 from 0 mod 10.

  • You can access a letter (or a digit) at a specified position in a string (or number) by using the letter () of [] block under “Operators”. For example: letter (4) of [18392819202910] //9

Show Scratch solution