Luhn Algorithm

  • Credit card validation is an important part of e-commerce and online transactions. In order to prevent fraud and ensure that transactions are secure, it's essential to verify that the credit card number entered by the user is valid. In this article, we'll explore how to validate credit card numbers using the Luhn algorithm in C.

What is the Luhn Algorithm?

The Luhn algorithm, also known as the "modulus 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, including credit card numbers. The algorithm works by summing up the digits of the number, starting from the rightmost digit and moving left. If the sum is divisible by 10, then the number is considered valid.

How does it work ?

  1. Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ digits together.

  2. Add the sum to the sum of the digits that weren’t multiplied by 2.

  3. If the total’s last digit is 0 (or, put more formally, if the total modulo 10 is congruent to 0), the number is valid!

An example;

For the sake of discussion, let’s first underline every other digit, starting with the number’s second-to-last digit:

4003600000000014

Okay, let’s multiply each of the underlined digits by 2:

1•2 + 0•2 + 0•2 + 0•2 + 0•2 + 6•2 + 0•2 + 4•2

That gives us:

2 + 0 + 0 + 0 + 0 + 12 + 0 + 8

Now let’s add those products’ digits (i.e., not the products themselves) together:

2 + 0 + 0 + 0 + 0 + 1 + 2 + 0 + 8 = 13

Now let’s add that sum (13) to the sum of the digits that weren’t multiplied by 2 (starting from the end):

13 + 4 + 0 + 0 + 0 + 0 + 0 + 3 + 0 = 20

Yup, the last digit in that sum (20) is a 0, so David’s card is legit!

So, validating credit card numbers isn’t hard, but it does get a bit tedious by hand. Let’s write a program.

The Code Let's take a look at the code for validating credit card numbers using the Luhn algorithm in C:

pseudocode:

1. Prompt the user to enter a credit card number
2. Read the credit card number from the user
3. Check if the credit card number is valid (greater than 0)
4. If the credit card number is not valid, go back to step 1
5. Extract the first few digits of the credit card number to determine the type of card
6. Initialize a variable to store the sum of the digits
7. While the credit card number is greater than 0:
   a. Get the last digit of the credit card number using the modulus operator
   b. Remove the last digit from the credit card number using integer division
   c. Increment a counter to keep track of the number of digits
   d. If the current digit is even (based on the counter):
      i. Double the digit
      ii. If the result is greater than 9, subtract 9 from it
   e. Add the current digit (or the doubled digit) to the sum
8. Check if the sum is divisible by 10
9. If the sum is divisible by 10:
   a. Check the first few digits of the credit card number to determine the type of card
   b. Print the name of the card (AMEX, MASTERCARD, VISA) or "INVALID"
10. If the sum is not divisible by 10, print "INVALID"
11. Terminate the program

The actual code:

#include <stdio.h>
#include <math.h>

int main()
{
    long int cc;
    int digit_count = 0;
    int sum = 0;

    //asks user for input of card number
    do
    {
        printf("Enter card number: ");
        scanf("%ld", &cc);
    }
    while (cc < 1);

    //variables that store the first numbers of the cards
    int amex = cc / pow(10, 13);
    int master = cc / pow(10, 14);
    int visa[2];
    visa[0] = cc / pow(10, 12);
    visa[1] = cc / pow(10, 15);

    //checksum for the luhn algorithm
    while (cc > 0)
    {
        int digit = cc % 10;
        cc /= 10;
        digit_count++;

        if (digit_count % 2 == 0)
        {
            digit *= 2;
            if (digit > 9)
            {
                digit -= 9;
            }
        }

        sum += digit;
    }

    //statements to check if cards are valid,american express, visa, mastercard or invalid
    //if the result of sum ends with 0 then this is a valid card from there we check the type of card it is
    if (sum % 10 == 0)
    {
        if (amex == 34 || amex == 37)
        {
            printf("AMEX\n");
        }
        else if (master == 51 || master == 52 || master == 53 || master == 54 || master == 55)
        {
            printf("MASTERCARD\n");
        }
        else if (visa[0] == 4 || visa[1] == 4)
        {
            printf("VISA\n");
        }
        else
        {
            printf("INVALID\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }

    //terminate the program
    return 0;
}
  • The code starts by asking the user to enter a credit card number. It then uses a do-while loop to ensure that the user enters a positive number.

  • Next, the code extracts the first few digits of the credit card number to determine the type of card. For example, American Express cards typically start with the digits 34 or 37, so the code divides the credit card number by 10^13 and stores the result in the amex variable. Similarly, Mastercard cards typically start with the digits 51, 52, 53, 54, or 55, so the code divides the credit card number by 10^14 and stores the result in the master variable. Visa cards can start with the digit 4, so the code divides the credit card number by 10^12 and 10^15 and stores the results in the visa array.

  • The code then applies the Luhn algorithm to the credit card number to calculate a checksum. The algorithm works by iterating over the digits of the number, starting from the rightmost digit and moving left. If the current digit is even, the code doubles it and subtracts 9 if the result is greater than 9. The code then adds the current digit (or the doubled digit) to a running sum.

  • Finally, the code checks if the checksum is valid by checking if the sum is divisible by 10. If the checksum is valid, the code checks the first few digits of the credit card number to determine the type of card. If the card is a valid American Express, Mastercard, or Visa card, the code prints the name of the card. Otherwise, the code prints "INVALID".

Conclusion: In this article, we've explored how to validate credit card numbers using the Luhn algorithm in C. We've seen how the algorithm works, and how to implement it in code using loops, conditionals, and arrays. We've also discussed how to extract the first few digits of a credit card number to determine the type of card. By following these steps, you can ensure that your e-commerce and online transactions are secure and free from fraud.

Last updated