Search code examples
ccs50

C get every other digit from an int


I'm following CS50 course of Harvard University and I have to create a program in C that finds if a credit card number is valid or not. For example, I want from this number 378282246310005 to get the every other digit like this 7224300 so I started like this:

printf("Number\n");
long long cardNum = GetLongLong();

I don't know the methods I need to use to get the other digits to make my calculations.


Solution

  • Make use of simple division (/) and % operator to get this

    int number[20];
    int count = 0;
    long long cardNum = GetLongLong();
    long long prevNum = cardNum;
    while (cardNum < 10)
    {
       cardNum = prevNum / 10;
       number[count] = prevNum % 10; 
       prevNum = cardNum;
    
       count++;
    }