Checking The Validity of a Credit Card in C [Luhn's Algorithm]

Checking the validity of a credit card might seem to be a pretty big task right ? But it is actually simple. The numbers allotted to the cards by the credit card companies always pass the Luhn's test. The following is the Luhn's algorithm.

Luhn's Algorithm

  •  Reverse the number.
  • Take the odd indexed elements and add them.
  • Take the even indexed elements and multiply each element by 2.
  • Add the sum of digits of the even indexed numbers. (ex : for 15 - 1 + 5 = 6)
  • Add the Odd Sum and the Even Sum.
  • If the result is divisible by 10, it is a valid number else it is invalid.

Example



It looks pretty simple right ? Yeah it is :) And so now let's implement this in our code. This is just simple mathematics but the only problem is the length of the number. You cannot input 16 digit number in a integer or long int or even a unsigned long int. So what we do is we just get the numbers as a character array. And we pass it into a switch case to convert that to a number array. We use that number array and perform the operations. The validate function validates the number and checks if it is a valid credit card number.




Output


Comments

Popular posts from this blog

Finding the Longest Palindrome in a String

Finding a Single Number amongst Repeated Numbers [Repeated Twice]

Finding the Longest Path From One Point To Another - Dynamic Programming