Validate a possible credit card number using C++

To write a program which helps validate a possible credit card number you will need to know two things. Some basic programming skills and the Luhn algorithm.

A short background on the Luhn algorithm

According to online sources the Luhn algorithm or modulus 10 was created by IBM scientist Hans Peter Luhn. The end result of his discovery, patented in 1960, is one that adds a level of integrity to a number which we can use for error reduction. A number known to be generated with this algorithm can be tested for errors after transmitting or recording using this simple method. These types of algorithms act a bit like hidden signatures. An alteration to a number generated with this algorithm is very very likely to change the signature and this change indicates the error. That’s basically it. All credit card numbers are defined with this algorithm built in.

Here it is in action using possible card number 4388576018410707 as an example:

  1. Beginning from the right, double every second digit (even digits).  If doubling results in a two digit number then add the single digits of the two digit number to get a single digit result.  In our example: [0x2=0], [0x2=0], [4×2=8], [1×2=2], [6×2=12, 1+2=3], [5×2=10, 1+0=1], [8×2=16, 1+6=7], [4×2=8]  These single digit results which I’ve highlighted in bold are then summed [0+0+8+2+3+1+7+8=29]
  2. Beginning again from right to left add all the of odd digits. In our example: [7+7+1+8+0+7+8+3=41]
  3. Sum the results from step 1 and step 2. [29+41=70]

If the result from step 3 is divisible by 10 then your number is considered valid!

The following is a simple program which performs this check.

I have not restricted the size of the number which allows the user to enter a number of almost any size. As you can see the entire program is written inside the main loop, without the use of functions or classes. If you are curious you can see this program rebuilt with functions in an article demonstrating c++ modularity.

Leave a Reply

Your email address will not be published. Required fields are marked *