C Program to count number of digits in a number

The following is a C program to count the number of digits in a number.

Expected Output:

1st run:

2nd run:

How it works

The following table demonstrates what happens at each iteration of the loop, assuming num = 123456.

Iteration rem num count
After 1st iteration rem = 123456%10 = 6   n = 123456/10 = 12345 count = 1
After 2nd iteration rem = 12345%10 = 5   n = 12345/10 = 1234 count = 2
After 3rd iteration rem = 1234%10 = 4   n = 1234/10 = 123 count = 3
After 4th iteration rem = 123%10 = 3   n = 123/10 = 12 count = 4
After 5th iteration rem = 12%10 = 2   n = 12/10 = 1 count = 5
After 6th iteration rem = 1%10 = 1   n = 1/10 = 0  count = 6

Recommended Reading:

Leave a Comment

%d bloggers like this: