Created
June 30, 2019 20:36
-
-
Save joel29dec/62b2b256e4a51353d4014c43504c5ff6 to your computer and use it in GitHub Desktop.
credit card validator in c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <math.h> | |
#include <stdio.h> | |
int main(void) | |
{ | |
// Declare and initialize cardname variable. | |
// Change variable below to test credit card number | |
long long cardnumber = 378282246310005; | |
// Determine whether it has a valid number of digits | |
int count = 0; | |
long long digits = cardnumber; | |
//checks for card length of 13, 15, or 16 | |
while (length > 0) | |
{ | |
length = length/10; | |
count++; | |
} | |
if ((count != 13) && (count != 15) && (count != 16)) | |
{ | |
printf("INVALID\n"); | |
} | |
// create array size with the count of the number | |
int number[count]; | |
// store each digit of card number in the array number | |
for (int i = 0; i < count; i++) | |
{ | |
number[i] = cardnumber % 10; | |
cardnumber = cardnumber / 10; | |
} | |
// number = [1,8,8,1,8,8,8,8,8,8,8,8,2,1,0,4] | |
int cardarray[count]; | |
for (int i = 1; i < count; i++) | |
{ | |
cardarray[i] = number[i]; | |
} | |
// multiply every other number in the array | |
for (int i = 1; i < count; i+=2) | |
{ | |
number[i] = number[i] * 2; | |
} | |
// cardarray = [8,8,1,8,8,8,8,8,8,8,8,2,1,0,4] | |
// number = [1,16,8,2,8,16,8,16,8,16,8,16,2,2,0,4] | |
int accumulator = 0; | |
int sumdigit; | |
if (count == 13) | |
{ | |
for (int i = 0; i < count; i++) | |
{ | |
sumdigit = (number[i] % 10) + (number[i]/10 % 10); | |
accumulator = accumulator + sumdigit; | |
} | |
if (cardarray[12] == 4 && accumulator % 10 == 0) | |
{ | |
printf("VISA\n"); | |
} | |
else | |
{ | |
printf("INVALID\n"); | |
} | |
} | |
if (count == 15) | |
{ | |
for (int i = 0; i < count; i++) | |
{ | |
sumdigit = (number[i] % 10) + (number[i]/10 % 10); | |
accumulator = accumulator + sumdigit; | |
} | |
if (cardarray[14] == 3 && accumulator % 10 == 0 && (cardarray[13] == 4 || cardarray[13] == 7)) | |
{ | |
printf("AMEX\n"); | |
} | |
else | |
{ | |
printf("INVALID\n"); | |
} | |
} | |
if (count == 16) | |
{ | |
for (int i = 0; i < count; i++) | |
{ | |
sumdigit = (number[i] % 10) + (number[i]/10 % 10); | |
accumulator = accumulator + sumdigit; | |
} | |
if (cardarray[15] == 4 && accumulator % 10 == 0) | |
{ | |
printf("VISA\n"); | |
} | |
else if (cardarray[15] == 5 && accumulator % 10 == 0 && (cardarray[14] == 1 || cardarray[14] == 2 || cardarray[14] == 3 || cardarray[14] == 4 || cardarray[14] == 5)) | |
{ | |
printf("MASTERCARD\n"); | |
} | |
else | |
{ | |
printf("INVALID\n"); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You did not initialize the variable "length"