I have been working on credit problem for edx CS50 and got it working as intended. an issue I find with it is the way I have to reinitialise the cardNumber
variable each time it enters a loop, and there are plenty of loops in my solution. Same goes for my bool value. Is there a better, cleaner way to go around this?
#include <stdio.h>
#include <cs50.h>
// Implement a program that determines whether a provided credit card number
// is valid according to Luhn’s algorithm.
int main(void)
{
long long userInput;
// Prompt for user input as long long.
do
{
userInput = get_long_long("Enter credit card number to validate: ");
// Ensure user inputs integer otherwise prompt "Retry: "
if (userInput < 0)
{
printf("Retry: \n");
}
} while (userInput < 0);
long long cardNumber = userInput;
int checkSum = 0;
int secDig, lastDig, multDig;
// start from second to last digit (cc_number / 10) % 10 and multiply every other digit by 2.
while (cardNumber > 0)
{
// sum digits that weren't multiplied.
lastDig = (cardNumber % 10);
// add the sum to the sum of the digits that weren't multipied by 2.
checkSum += lastDig;
secDig = (cardNumber / 10) % 10;
cardNumber /= 100;
// multiply every other digit
multDig = secDig * 2;
// add those products (separate /10, return modulus of 10) digits together.
if (multDig > 10)
{
checkSum += (multDig % 10) + 1;
}
else if (multDig == 10)
{
checkSum += 1;
}
else
{
checkSum += multDig;
}
}
// validate checksum
// if sum of digits ends in 0 ergo % 10 = 0 then number is valid.
bool valid = false;
if (checkSum % 10 == 0)
{
valid = true;
}
int numOfDigits = 0;
cardNumber = userInput;
// validate number's length
// track number's length
while (cardNumber > 0)
{
cardNumber /= 10;
numOfDigits++;
}
cardNumber = userInput;
// validate company's identifier
// if 15 digits, starts with 34 or 37 - AMEX
if (valid == true && numOfDigits > 12)
{
if (numOfDigits == 15)
{
for (int i = 0; i < numOfDigits - 2; i++)
{
cardNumber /= 10;
}
if (cardNumber == 34 || cardNumber == 37)
{
printf("AMEX\n");
valid = true;
}
else
{
valid = false;
}
}
// if 16 digits, starts with 51-55 - MASTERCARD
cardNumber = userInput;
if (numOfDigits == 16)
{
for (int i = 0; i < numOfDigits - 2; i++)
{
cardNumber /= 10;
}
if (cardNumber >= 51 && cardNumber <= 55)
{
printf("MASTERCARD\n");
valid = true;
}
else
{
valid = false;
}
}
// if 13 OR 16 digits, starts with 4 - VISA
cardNumber = userInput;
if (numOfDigits == 13 || numOfDigits == 16)
{
for (int i = 0; i < numOfDigits - 1; i++)
{
cardNumber /= 10;
}
if (cardNumber == 4)
{
printf("VISA\n");
valid = true;
}
else
{
valid = false;
}
}
if (valid == false)
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
}
All comments are part of pseudocode for this solution. I left them there to satisfy style50. I would appreciate advice so I can write cleaner next time and make it into a habit. I am a beginner starting CS degree next year with only experience with doing C# courses with Mosh Hamedani.