How can I get a very large number to get printed a digit (its remainder) at a time? (a credit card validation code)

Viewed 36

I'm working on a code to verify valid credit card numbers. I'll be using the Luhn algorithm logic eventually, But first I'm trying to store the single digits of the card number into an array of size 20. Since there is no way to split an integer (integer here is the credit card number) I thought of getting the remainder of the integer by dividing by 10 (This way I can get the individual digits). However, my problem is that when the size of the integer becomes 11 or more, only a few digits are getting stored and with the wrong values. I just started to learn C programming and would really appreciate it if someone could help me, Thank you.

Note: I have given -1 to the 0th index of the array to say that it's the end of the card number. eg: 123467321234-1

Code :

#include <stdio.h>

int main() {
    long int cardNo[20];
    long int input_cardNo;
    int cardNo[0] = -1;                                //card number ends here
    int i = 1;

    printf("Enter your card number : ");
    scanf("%d", &input_cardNo);

    do {
        long int remainder = input_cardNo % 10;        //getting the remainder of card number
        long int division  = input_cardNo / 10;        //getting the div value of card number
        cardNo[i] = remainder;                         //assigning the remainder value to an [i] index in the array
        printf("%d\n", cardNo[i]);
        input_cardNo = division;                       //updating the card number with the div vale
        i++;
    } while (input_cardNo != 0);

    return 0;
}
1 Answers

Just a brief explanation why long int does not work.

For most operating systems long int stores have the same capacity as int, it stores from -2^31 to 2^31 - 1. See: Long Vs. Int C/C++ - What's The Point?

With this, the maximum value is: 2147483648 or around 9-10 digits for your case. You may use long long int to store up to 4.611686e+18 or 17-18 digits.

Related