1

I am trying to show the value of the second sum in the checksum function for a credit card validation program. However, it is not showing the proper value. For example, when I am using this credit card number (4003600000000014), the first sum shows the proper value of 7, but the second one shows a value of 30 000 something. Here is the code:

# include <stdio.h>
# include <cs50.h>
# include <math.h>

// Declaration of the functions
long get_number(void);
void check_len(long cc);
bool checksum(long cc);

// Main program
int main(void)
{
    //Declaring the variable to store the credit card number inputed by the user
    long credit_number = get_number();

    //Validation of the credit card number provided
    if(checksum(credit_number) == true)
    {
        check_len(credit_number);
    }
    else
    {
        printf("INVALID\n");
    }
}

// Function that prompt the user for a credit card number
long get_number(void)
{
    // Declaration of the credit card variable
    long number;

    // Ask the user for a credit card number. If it's not none-negative, keep asking
    do
    {
        number = get_long("Enter credit card number: ");
    }
    while (number <= 0);
    return number;
}

// Function to check the type of credit card
void check_len(long cc)
{
    // Declaration of variables
    int i;
    long number = cc;

    // Count the len of the provided credit card number
    for (i = 0; cc != 0; i++)
    {
        cc = cc/10;
    }
    printf("The len is: %i\n", i);

    // Validate the type of card: AMEX, MASTERCARD or VISA
    if (i == 15)
    {
        if ( (number >= 34e13 && number < 35e13) || (number >= 37e13 && number < 38e13) )
        printf("AMEX\n");
        else
        {
            printf("INVALID\n");
        }
    }
    else if (i == 13 || i == 16)
    {
        if ( (number >= 51e14  && number < 56e14) )
        {
            printf("MASTERCARD\n");
        }
        else if ( (number >= 4e12 && number < 5e12) || (number >= 4e15 && number <= 5e15) )
        {
            printf("VISA\n");
        }
        else
        {
            printf("INVALID\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }
}

bool checksum(long cc)
{
    bool valid_sum = true;
    int last_digit;
    int sum;
    int second_last;
    int second_sum;
    int total;
    long cc_2 = cc;

    while (cc > 0)
    {
        last_digit = cc % 10;
        sum = sum + last_digit;
        cc = cc / 100;
        printf("%i\n", last_digit);
    }
    printf("The sum is: %i\n", sum);

   while (cc_2 > 0)
    {
        second_last = (cc_2 % 100) / 10;
        second_sum = second_sum + second_last;
        cc_2 = cc_2 / 100;
        printf("%i\n", second_last);

    }
    printf("The second sum is: %i\n", second_sum);

    return valid_sum;
}
ChuChu
  • 29
  • 2

0 Answers0