0

I'm currently three lectures into cs50 as a completely new programmer and I am enjoying it tremendously!

I've enjoyed struggling on mario(less/more comfortable) and cash but right now I'm at a complete loss with credit pset1. My code is hitting a brick wall at the end and I'm not sure how to continue.

The problem im facing is that after printing out the second from last digits in a given input, I'm not sure how to "save" these digits so that I can multiply them by two and add them together to validate the credit card number...

Would appreciate any form of input!

#import <cs50.h>
#import <stdio.h>

int main(void)
{
    long long x;

    // Prompts for positive integer from user

    do 
    {
    x = get_long_long("Number: ");
    }

    while (x < 0);

    // Create new integer variable (y) to represent number of digits(initializes at zero)

    int y = 0;

    // Create new variables for use later on...
    // long long (h) will be used to store input value of x since value of x will be manipulated to find digits later...
    // long long (z) will be used as a temp placeholder for future variable t,
    // long long (t) will be used in conjunction with mod 10 in a simple formula to find the second last digit...

    long long h;
    h = x;
    long long z = h / 10;
    long long t;


    // Find number of digits in user's value by creating while loop(digit count+1 after every division by 10)

    while (x > 0)
    {
        x /= 10;
        y ++;
    }

    printf("Amount of digits: %d\n", y);

    // Run validity check based on amount of digits

    if ((y != 13) && (y != 15) && (y != 16))
    {
        printf("INVALID\n");
    }

    // Create for loop to print every second digit starting from the last
    for (int p = 1; p < y; p++)
    {
        t = z % 10;
        printf("%lld\n", t);
        z /= 100;
    }

}
1

You could create a new variable outside of the while loop called result, and initialize it to 0.

Then, inside the while loop, after you get the second to last digit, you can double it, and then loop through the digits of the product and add every one of them to result.

Please let me know if this helps you, and if there's anything you don't understand, feel free to ask me in the comments.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .