0

C language question. My task is to get second to the last, third to the last digit etc. from a long. Got a hint to do it by using modulo operator:

int main(void)
{
    a = get_long("n:\n");

    mod = a % 10;

    printf("%i", mod);
}

Works great for the rightmost digit but I just can't figure it out how to get second-, third-to the last digit, and so on. I am trying to put the function into a for loop but it does not work at all. Do you have any ideas how to accopmlish that?

I am not looking for a ready solution - just for the path to follow.

piotrektnw
  • 120
  • 7
  • a % 10, a / 10, a % 10, a / 10... – Lundin Jun 18 '20 at 10:29
  • 1
    seems like a dupe of [Getting each individual digit from a whole integer](https://stackoverflow.com/questions/3118490/getting-each-individual-digit-from-a-whole-integer) or others that can be found by searching – underscore_d Jun 18 '20 at 10:30
  • This seems like processing a card number. Input a string, instead of an integer. The digit characters are all laid out for you. Always use strings for card and phone numbers. – Weather Vane Jun 18 '20 at 10:32
  • 1
    Notice that `1234 / 10 == 123`. The rest should be easy. – HolyBlackCat Jun 18 '20 at 10:38
  • 1
    "I am trying to put the function into a for loop but it does not work at all." No need to hide your attempts. – Gerhardh Jun 18 '20 at 10:39

1 Answers1

2

You started off right, the first iteration will give you the rightmost digit. After that, you need to reduce the original number in a way such that the one but last number becomes the last one.

Solution: Divide by 10. Every time you divide the number by 10 (integer division), the rightmost digit disappears and the last but one digit becomes the last digit. So, you can keep using the same login with modulo to obtain the new last digit.

Something like

int main(void)
{
    int a = get_long("n:\n"); //why no datatype?

    int mod = -1;

    for (; a > 0; a/=10){  // check if a> 0, perform the modulo, and then divide by 10
        mod = a % 10;
        printf("%i\n", mod);
    }
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thank You, I see it working but please explain to me How is it working? Why 'mod' has to be -1 at the beginning? – piotrektnw Jun 18 '20 at 22:00
  • @piotrektnw It's the same step, repeated multiple times. Use a pen and paper and do the calculation, or run the program through a debugger, it'll be easier to understand. and regarding the `-1`, it's just a value used for initialization, no specific significance. – Sourav Ghosh Jun 19 '20 at 09:27