Check for valid credit card number

Challenge Level: Ready to expand

Learning outcomes

Students will be able to:

Requirement:

Write a program that asks the user to enter a credit card number (16 digits) as the input and says if the credit card number is valid as the output.

Testing examples:

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

Important: None of these are actual credit card numbers, but the correct ones have the correct checksum.

Input Output
5105105105105100 Valid credit card number!
4111111111111111 Valid credit card number!
4012888888881881 Valid credit card number!
5105105505105100 Invalid credit card number!
4111112111111111 Invalid credit card number!
4112888888881881 Invalid credit card number!

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

ask [Enter a credit card number:] and wait
repeat (8)
end

if <((letter (index) of (credit card number)) * (2)) < [10]> then
else
end

if <(((even total) + (odd total)) mod (10)) = [0]> then
else
end
say [Invalid credit card number!]

say [Valid credit card number!]
set [index v] to [1]

set [credit card number v] to [0]

set [even total v] to [0]

set [odd total v] to [0]

change [credit card number v] by (answer)

change [odd total v] by ((letter (index) of (credit card number)) * (2))

change [index v] by (1)

change [odd total v] by (((letter (index) of (credit card number)) * (2)) - (9))

change [index v] by (1)

change [even total v] by (letter (index) of (credit card number))

change [index v] by (1)
Hints
  • Every second number (the odd digits of the credit card, i.e. 1st, 3rd, 5th, and so on digits) is multiplied by 2, 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 of the credit card. The credit card number is valid if the final total is a multiple of 10 (i.e. total mod 10 is equal to 0).

Show Scratch solution