-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreditCardValidator.cpp
More file actions
41 lines (37 loc) · 1.01 KB
/
creditCardValidator.cpp
File metadata and controls
41 lines (37 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Using Luhn's algorithm to validate credit card numbers.
#include <iostream>
bool isValidCreditCard(const std::string &cardNumber);
int main() {
std::string cardNumber;
std::cout << "Enter your credit card number: ";
std::cin >> cardNumber;
if (isValidCreditCard(cardNumber)) {
std::cout << "Valid credit card number" << std::endl;
} else {
std::cout << "Invalid credit card number" << std::endl;
}
return 0;
}
bool isValidCreditCard(const std::string &cardNumber) {
int sum = 0;
for (int i = cardNumber.length() - 1; i >= 0; i -= 2) {
int digit = cardNumber[i] - '0';
digit *= 2;
if (digit > 9) {
digit -= 9;
}
sum += digit;
}
int oddSum = 0;
for (int i = cardNumber.length() - 2; i >= 0; i -= 2) {
int digit = cardNumber[i] - '0';
if(digit % 2 != 0) {
oddSum += digit;
}
}
if ((sum + oddSum) % 10 == 0) {
return true;
} else {
return false;
}
}