0

After working on this problem for 5+ hours I was able to get the code working. After I summitted it, I looked at other peoples solutions, and most of them were very different than mine. Is the style of the code too drawn out or inefficient?

//prompt user for card number
long card;
card = get_long("Card:");

//determine length of card number
long card2 = card;
int digits = 0;
while (card2 > 0)
{
    card2 = card2 / 10;
    digits++;
}
int digits2 = digits;

//determine if digit count is valid
if (digits != 13 && digits != 15 && digits != 16)
{
    printf("INVALID\n");
    return 0;
}

//get every other number from second to last
int amount = digits / 2;
long card3 = card;
int sum1 = 0;
int setup = 0;
int variable;

for (int x = 0; amount != x; x++)
{
    card3 = card3 / 10;
    variable = card3 % 10;
    card3 = card3 / 10;

    //multiply by two
    setup = variable * 2;

    //add digits to get sum
    while (setup > 0)
    {
        sum1 = sum1 + setup % 10;
        setup = setup / 10;
    }
}

//add every other digit together
long card4 = card;
int variable2;
int sum2 = 0;

while (card4 != 0)
{
    variable2 = card4 % 10;
    card4 /= 10;
    card4 /= 10;
    sum2 += variable2;
}

//add sum1 and sum2
int sum3 = sum1 + sum2;

//check if last digit is zero
sum3 = sum3 % 10;
if (sum3 != 0)
{
    printf("INVALID\n");
    return 0;
}

//find first two numbers of card number
for (int x = digits2 - 2; x != 0; x--)
{
    card = card / 10;
}

//determine the type of credit card
if (card == 34 || card == 37)
{
    printf("AMEX\n");
}
else if (card >= 51 && card <= 55)
{
    printf("MASTERCARD\n");
}
else if (card / 10 == 4)
{
    printf("VISA\n");
}
else
{
    printf("INVALID\n");
    return 0;
}

Thanks :)

You must log in to answer this question.

Browse other questions tagged .