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

Length is always 3, examples:

000 056 999 

How to get a number so that I can use the value of one digit in the array?

Would it be easier to convert to char , iterate over it and convert it back to int if necessary?

+4
source share
2 answers

To get the decimal digit at position p integer i , you do the following:

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

So, to iterate over the last digit in the first digit, you must do the following:

 int n = 56; // 056 int digit; while(n) { digit = n % 10; n /= 10; // Do something with digit } 

Easy to change to do it exactly 3 times.

+6
source

As Austin says, you can easily find answers on Google. But basically it includes mod-by-10, then split by ten. Assuming integers.

-3
source

All Articles