I need some help with a programming assignment on C++(Raspbian). We have to user
ID: 3766516 • Letter: I
Question
I need some help with a programming assignment on C++(Raspbian). We have to user Luhn's Algorithm to figure out if a credit card number is valid or not. I need to use #include <stdio.h> #include<stdlib.h> and #include<string.h>.
So first I have to ask the user for a 16 digit credit card number then I just have to tell the user if it is valid or not.
The basic steps of the algorithm is:
• Double all even-positioned digits when counting from right to left.
• Determine the sum of the undoubled digits from the products (Step 1) and each of
the unaffected (odd-positioned) digits in the original number.
• Verify the account number by determining if the sum from step 2 is a multiple of 10.
Along with the main function I have to use the following three functions:
1. readCC: Read in the 16-digit credit card number, and return it to main.
The number should be read in as a string and converted to be
stored in an integer array, which is returned from the function.
The function should also validate that the ISBN entered has the
correct number of digits before proceeding with checking its
validity. If it does not have the correct number of digits, provide
an appropriate error message and exit the program.
2. isValid: Take the credit card number as input, and check its validity,
outputting an appropriate message to the user. This function
calls the function runLuhn, which returns a checksum. If the
value returned is zero, the number is valid, if non zero, it is not
valid.
3: runLuhn Take the credit card number as input and calculate the checksum
using Luhn’s algorithm, returning its value (i.e. the remainder
obtained when the sum value calculated is divided by 10).
My program should work on the following:
5105-1051-0510-5100 Valid
5111-1111-1111-1118 Valid
5555-5555-5555-4444 Valid
4012-8888-8888-1881 Valid
4408-0412-3456-7890 Invalid
4417-1234-5678-9112 Invalid
Note: I have to use the functions that I mentioned above so can someone please help.
Thanks
Explanation / Answer
The input strings should look like
5105105105105100
5111111111111118
5555555555554444
4012888888881881
4408041234567890
4417123456789112
#include <bits/stdc++.h>
using namespace std;
void readCC(int * arr){
string s;
cin>>s;
if(s.length()==16){
for(int i=0;i<16;i++){
arr[i]=s[i]-'0';
}
}
else{
cout<<"You have entered an invalid card number."<<endl;
}
}
int sumofdigits(int n){
int ans=0;
while(n>0){
ans+=n%10;
n=n/10;
}
return ans;
}
int runLuhn(int * arr){
int arr1[16];
for(int i=0;i<16;i++){
if(i%2!=0){
arr1[i]=arr[i];
}
else{
arr1[i]=sumofdigits(arr[i]*2);
}
}
int sum=0;
for(int i=0;i<16;i++){
sum+=arr1[i];
}
return sum%10;
}
bool isValid(int * arr){
if(runLuhn(arr)==0){
return true;
}
return false;
}
int main(){
int * arr=new int[16];
for(int i=0;i<16;i++){
arr[i]=(-1);
}
readCC(arr);
if(isValid(arr)){
cout<<"Valid"<<endl;
}
else{
cout<<"invalid"<<endl;
}
return 0;
}