Suteemon Vararatsamenitikul
last year
Suteemoncountry asked

How can I loop through each digit in an integer?

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

Hi Suteemon,

Great question — if you want to loop through each digit of an integer (not each number in a range), you can do it using division and modulus.

Here’s how you can do it in C:

int num = 1234;

while (num > 0) {
    int digit = num % 10;  // gets the last digit
    printf("%d\n", digit); // print or process the digit
    num = num / 10;        // remove the last digit
}

This will print:

4  
3  
2  
1

If you want the digits in the original order (1, 2, 3, 4), you can store them in an array or reverse them after collecting.

Let me know if you were asking about looping over a range of numbers instead — happy to help with that too.

If you have more questions, I am here to help.

C
This question was asked as part of the Practice: C Programming course.