Skip to content

Instantly share code, notes, and snippets.

@sameekapdi
Created September 7, 2017 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sameekapdi/71524d8bb328145b559948896c1abd87 to your computer and use it in GitHub Desktop.
Save sameekapdi/71524d8bb328145b559948896c1abd87 to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
long long cc_num;
//Get User input
do
{
printf("Please enter your credit card number: ");
cc_num = get_long_long();
} while (cc_num < 0);
//Determine the length of the credit card number
int length = 0;
long long chk_length = cc_num;
while (chk_length >0)
{
chk_length /= 10;
length++;
}
//Separate credit card number into an array
int number[length];
for (int i =0; i < length; i++)
{
number[i] = cc_num % 10;
cc_num /= 10;
}
//Calculate sum of every other digit from the last.
int added_sum = 0;
for (int i =0; i < length; i+=2)
{
added_sum += number[i];
}
//Calculate the sum of every other digit from 2nd to last times 2
int x2_sum = 0;
for (int i = 1; i<length; i+=2)
{
if (number[i]*2 > 9)
{
x2_sum += (number[i] * 2) / 10;
x2_sum += (number[i] * 2) % 10;
}
else
{
x2_sum += number[i] * 2;
}
}
//Check to see if card is valid and what type of card it is
int checksum = added_sum + x2_sum;
if (checksum % 10 == 0 && (length == 13 || length ==15 || length == 16))
{
if (number[length-1] == 3 && (number[length-2] == 4 || number[length-2] == 7))
{
printf("AMEX\n");
}
else if (number[length-1] == 5 && (number[length-2] == 1 || number[length-2] == 2 || number[length-2] == 3 || number[length-2] == 4 || number[length-2] == 5))
{
printf("MASTERCARD\n");
}
else if (number[length-1 == 4])
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment