#include<iostream>
#include<string>
using namespacestd;
intmain() {
cout << "Enterthe card number: ";
string cardNumber;
cin >>cardNumber;
bool valid = true;
int sumOfOdd = 0;
int sumOfEven = 0;
// The credit card number muststart with 3, 4, 5 or 6.
if ((cardNumber[0] != '3') && (cardNumber[0] != '4') && (cardNumber[0] != '5') && (cardNumber[0] != '6')) {
valid = false;
}
// The total number of digits ofa credit card number must be between 13 to 16 digits.
if ((cardNumber.length() < 13) || (cardNumber.length() > 16)) {
valid = false;
}
// Luhn Rule
for (int i = 0; i <cardNumber.length(); i++) {
char c =cardNumber[cardNumber.length() - i - 1];
intnum = c - '0';
if ((num< 0) || (num> 9)) {
valid = false;
}
if (i % 2 == 1) {
num = 2 *num;
if (num> 9) {
num =num / 10 +num % 10;
}
sumOfEven =sumOfEven + num;
}
else {
sumOfOdd =sumOfOdd + num;
}
}
int sum =sumOfOdd + sumOfEven;
if (sum% 10 != 0) {
valid = false;
}
if (valid) {
cout << "Thecard is valid" << endl;
}
else {
cout << "Thecard is invalid" << endl;
}
return 0;
}
Comments
Leave a comment