I have completed the other set one problems, and wanted to test myself with "Credit". I read through the problem and walk through and wrote code that I believed would work. I tested the code and it only ever prints "INVALID" so at least one part of my code is working, but I can't for the life of me figure out which parts of my code aren't working as intended.
Please can someone with more experience look at this code and explain what I'm doing wrong as well as what I should change for the code to work properly.
Thanks in advance!
#include <stdio.h>
bool checksum(long card_number);
int checknum(long card_number);
int startnum(long card_number);
bool valid = false;
int num = 0;
int first = 0;
int second = 0;
int main(void)
{
// prompt user for credit card number
long card_number;
do
{
card_number = get_long("Number: ");
}
while (card_number < 0);
// check if the card is valid using a checksum
valid = checksum(card_number);
// check how many numbers the card has
num = checknum(card_number);
// check what numbers the card starts with
first = startnum(card_number);
second = startnum(card_number);
// print the type of card to the user, or invalid
if (num == 15 && valid == true)
{
printf("AMEX\n");
}
else if ((num == 13 || num == 16) && valid == true && first == 4)
{
printf("VISA\n");
}
else if (num == 16 && valid == true && first == 5 && (second == 1 || second == 2 || second == 3 || second == 4 || second == 5))
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
}
bool checksum(long card_number)
{
long multiplier;
int sum = 0;
for (multiplier = 100; multiplier < 10000000000000000; multiplier = multiplier * 100)
{
int digit = card_number % multiplier;
sum = sum + (digit * 2);
return sum;
}
if (sum % 10 == 0)
{
valid = true;
}
else
{
valid = false;
}
return valid;
}
int checknum(long card_number)
{
if (card_number % 10000000000000000 == 0)
{
if (card_number % 1000000000000000 == 0)
{
if (card_number % 100000000000000 == 0)
{
if (card_number % 10000000000000 == 0)
{
if (card_number < 1000000000000)
{
num = 0;
}
else
{
checksum(card_number);
}
}
else
{
num = 13;
}
}
else
{
num = 14;
}
}
else
{
num = 15;
}
}
else if (card_number > 9999999999999999)
{
num = 0;
}
else
{
num = 16;
}
return num;
}
int startnum(long card_number)
{
if (num == 16)
{
first = card_number % 10000000000000000;
if (first == 5)
{
second = card_number % 1000000000000000;
}
}
return first;
return second;
}