I am using following code to implement Luhn algorithm for credit card check in c# language but could not get the output to generate the check sum its showing validity: kindly help me.Thank you in advance
public class Program
{
private static void Main(string[]creditcard)
{
int sum = 0, d;
string num ="7992739871";
int a = 0;
for (int i = num.Length - 2; i >= 0; i--)
{
d = Convert.ToInt32(num.Substring(i, 1));
if (a % 2 == 0)
d = d * 2;
if (d > 9)
d -= 9;
sum += d;
a++;
}
if ((10 - (sum % 10) == Convert.ToInt32(num.Substring(num.Length - 1))))
Console.WriteLine("valid");
Console.WriteLine("sum of digits of the number" + sum);
}
}
Here are some extension methods that compute a Luhn checkdigit, validate a number with a checkdigit, and add a checkdigit to a number. Tested in .NET 4.5.
There are extension methods for strings, ints, int64s and IList.
I got some ideas for this from rosettacode.org
Here are some XUnit test cases that show how the extension methods work.
Compact Luhn check:
Fiddle: https://dotnetfiddle.net/CCwE48
This one will do it I believe:
Your algorithm is correct, but you're testing it wrong way.
I can see your sample input is from wiki page: Luhn algorithm. Difference is, they are calculating check digit for
"7992739871X"
, whereX
is the check digit they're looking for. Your code validates number your already have!Change your input to
"79927398713"
and it will mark it as correct number.Update
OK, I see where is the problem. You're not taking this part of algorithm right:
Your code takes every other digit, but not necessary starting from most left digit. Try this code:
You can do it very simply (reference),