Calculate the last digit of a credit card number

Learning outcomes

Students will be able to:

Requirement:

Write a program that asks the user to enter the first 15 digits of a credit card number as the input and says what the last digit should be as the output.

Testing examples:

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

Important: None of these is an actual credit card number, but the correct ones have the correct checksum.

Input Output
510510510510510 The last digit of the credit card is: 0
411111111111111 The last digit of the credit card is: 1
401288888888188 The last digit of the credit card is: 1

Languages

Scratch

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

say (join [The last digit of the credit card should be: ] (((0) - ((total 2) + (total 1))) mod (10)))

ask [Enter the first 15 digits of the credit card:] and wait
if <((letter (index) of (first 15 digits)) * (2)) < [10]> then
else
end

repeat (7)
end

repeat (8)
end
set [index v] to [1]

set [first 15 digits v] to [0]

set [total 2 v] to [0]

set [total 1 v] to [0]

set [first 15 digits v] to (answer)

change [total 1 v] by ((letter (index) of (first 15 digits)) * (2))

change [index v] by (2)

change [total 1 v] by (((letter (index) of (first 15 digits)) * (2)) - (9))

change [index v] by (2)

set [index v] to [2]

change [total 2 v] by (letter (index) of (first 15 digits))

change [index v] by (2)
Hints
• For the first 15 digits of the credit card, multiply every odd digit by 2 (i.e. 1st, 3rd, 5th, and so on digits), but if this gives a 2-digit number you should subtract 9 from it. For example, if the input digit 8 is multiplied by 2, that gives 16, and subtracting 9 from that gives 7 to add to the running total (some descriptions of the method say that you should add the two digits together, which gives the same result e.g. for 8x2 = 16 adding the digits in the result is 1+6, which is also 7).

• You then add the sum of these values to the sum of the even digits. The last digit (check digit) is calculated by subtracting the final total from 0 mod 10.