My solution to credit in pset1 compiles without issue but prints INVALID regardless of whether or not the card number is valid. I've attempted to diagnose the problem to no avail.
I used string indexes and for loops to multiply every second number by two (starting with the second to last number), sum their digits, and add the resulting sum to the sum of the non-multiplied numbers.
Beginner programmer here, any help is thoroughly appreciated.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
// This program determines whether or not a number is a valid credit card number
// If the number is valid, the program prints the type of card
int main(void)
{
// Get card number from user and declare variables
char *cardNum;
do
{
cardNum = get_string("Give me a card number: ");
}
while (atoll(cardNum) < 0);
int i;
int x;
// Multiply every other digit by 2 and then add those products' digits together
int accum1 = 0;
for (i = (strlen(cardNum) - 2); i >= 0; i -= 2)
{
int y = (((cardNum[i]) - '0') * 2);
char ys[12];
sprintf(ys, "%i", y);
accum1 += (ys[0] - '0');
}
// Sum the digits not multiplied by 2 in previous loop
int accum2= 0;
for (x = (strlen(cardNum) - 1); x >= 0; x -= 2)
{
accum2 += (cardNum[x] - '0');
}
// Check if number is valid and print card type
if ((accum1 + accum2) % 10 == 0)
{
if (cardNum[0] - '0' == 3 && (cardNum[1] - '0' == 4 || cardNum[1] - '0' == 7))
{
printf("AMEX\n");
}
if (cardNum[0] - '0' == 5 && (cardNum[1] - '0' == 1 || cardNum[1] - '0' == 2 || cardNum[1] - '0' == 3 || cardNum[1] - '0' == 4 || cardNum[1] - '0' ==5))
{
printf("MASTERCARD\n");
}
if (cardNum[0] - '0' == 4)
{
printf("VISA\n");
}
}
// Print "Invalid" if number is not a valid card number
else
{
printf("INVALID\n");
}
return 0;
}