piotrektnw
piotrektnw

Reputation: 120

Modulo in order to get single int from long

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.

Upvotes: 0

Views: 2447

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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);
    }
}

Upvotes: 2

Related Questions