user869778
user869778

Reputation: 243

How can I iterate through each digit in a 3 digit number in C?

Length is always 3, examples:

000
056
999

How can I get the number so I can use the value of the single digit in an array?

Would it be easier to convert to an char, loop through it and convert back to int when needed?

Upvotes: 4

Views: 8489

Answers (1)

Ry-
Ry-

Reputation: 224913

To get the decimal digit at position p of an integer i you would do this:

(i / pow(p, 10)) % 10;

So to loop from the last digit to the first digit, you would do this:

int n = 56; // 056
int digit;    

while(n) {
    digit = n % 10;
    n /= 10;

    // Do something with digit
}

Easy to modify to do it exactly 3 times.

Upvotes: 6

Related Questions