# Credit Card Checksum

#### dzieger

##### New Coder
I started edX CS50 and I'm working on a program that checks if a credit card number is valid by checking that it has the right amount of digits, the starting digits are correct, and then using luhns algorithm and returns either the card name if it is valid or invalid. It all works for the most part however, the valid visa cards i've entered return as invalid and some american express numbers don't give a read back. i'm assuming the problem is in the if statements but ill provide a a copy of the file. If anyone could help it would be much appreciated.

IF statements to determine card validity:
``````    //starts checks to see if the card is valid

//validates if it is american express card
if (count == 15) //total digits
{
if (num == 34 || num == 37) //starting numbers of cards
{
if (sumt % 10 == 0) //luhns algorithm
{
printf("AMEX\n");
}
}
else
{
printf("INVALID\n");
}
}
//validates if it is mastercard
else if (count == 16) //total digits
{
if (num == 51 || num == 52) //starting digits
{
if (sumt % 10 == 0) //luhns algorithm
{
printf("MASTERCARD\n");
}
}

else if (num == 53 || num == 54) //starting digits
{
if (sumt % 10 == 0) //luhns algorithm
{
printf("MASTERCARD\n");
}
}
else if (num == 55) //starting digits
{
if (sumt % 10 == 0) //luhns algorithm
{
printf("MASTERCARD\n");
}
}
else
{
printf("INVALID\n");
}
}
//validates if its visa
else if (count == 13 || count == 16) //total digits
{

if (vnum == 4) //first digit
{
if (sumt % 10 == 0) //luhns algorithm
{
printf("VISA\n");
}
}
}
else
{
printf("INVALID\n");
}
}``````

#### Attachments

• credit.zip
842 bytes · Views: 1

#### swift

##### Coder
This was interesting, thanks for sharing the code! I ended up reading about Luhn's algorithm, since finishing my CS degree many years ago I don't generally encounter things like this.

Anyway, I think you make life more difficult for yourself with the nested if statements. There are a lot of different paths through this code (lookup cyclomatic complexity as a measure of this). You'd benefit greatly from extracting some of the repeated parts of the code out (eg. checking modulus of sumt).

Your problem lies in the fact that you check the modulus but if that's invalid then nothing happens. I could enter 5100000000000000 and get no response because although it's 16 characters and begins with a 51 the nested luhn's algo check doesn't have an else case to deal with an invalid checksum.

Hope that makes sense!

Replies
0
Views
62
Replies
3
Views
409
Replies
6
Views
538
Replies
4
Views
446