Your Card is Valid

When you type a credit card number on a website, or scan the card into a physical device, a quick calculation is performed to ensure that the card number is valid. This check happens before the bank is contacted to verify the account and the amount. The technique used to perform the quick calculation is known as the MOD 10 algorithm.

A credit card number is 16 digits long. The first digit determines the card type:

3 is American Express
4 is Visa
5 is MasterCard
6 is Discover

Somewhere in the middle is the account number. And the final digit is a check digit, which is used in the MOD 10 algorithm to ensure that the number is valid. Here is how that algorithm works:

  1. Take all the digits in the card number, except for the final digit (the check digit) and double every other digit.
  2. If a doubled-digit is greater than 9 (two-digits wide), add the digits. So the value 14 (double 7) changes into 5.
  3. Add the digits together.
  4. Multiply the result by 9.
  5. Compare the last digit of the result with the check digit.

If the last digit of the result matches the check digit, then the card number is valid.

Here is an example credit card number. It’s not tied to any account, yet it should be valid:

4024007180064163

The number starts with 4, so it’s a Visa card. The check digit is 3.

1. Double every other digit (but not the final, check digit):

4 0 2 4 0 0 7 1 8 0 0 6 4 1 6

And get:

8 0 4 4 0 0 14 1 16 0 0 6 8 1 12

2. Perform a digit-sum on anything greater than 9:

8 0 4 4 0 0 5 1 7 0 0 6 8 1 3

3. Tally the digits:

8+0+4+4+0+0+5+1+7+0+0+6+8+1+3 = 47

4. Multiply the result by 9:

47 * 9 = 423

5. Compare the last digit of the result with the check digit:

423 = 3 = 3

And the card number is valid.

For this month’s Exercise, your job is to implement the MOD 10 algorithm in C. Use the following array in your code as five sample card numbers to verify:

    char *card[5] = {
        "4485113397627032",
        "6011621789921290",
        "5542619587695576",
        "5107425739448074",
        "4556114306308858"
    };

Your code must display each number processed, whether or not it’s a valid number, and the type of card: Visa, Discover, or Mastercard. (An American Express card sample isn’t included in the card[] array.)

These card numbers, as well as the algorithm’s description, were obtained from the GetCreditCardNumbers website. This site generates valid, unused credit card numbers so that programmers can test their algorithms.

Click here to read my solution, but please try this Exercise on your own before you see how I solved it.

Leave a Reply