Number Of Digits
On the previous page we talked about assignments like i = i - 1
, x = x + 10
, or a = a * 5
. Let's look at one specific assignment of this kind:
int x = 1234;
x = x / 10;
x = x / 10;
x = x / 10;
x = x / 10;
What would the value of x
be after these divisions?
1234 is not divisible by 10, so if we divided them as real numbers, we would've got 123.4; but we only use the int
whole numbers type for now, so the integer division will drop the fractional part, giving us 123 as a result. The remaining 4 can be found by calculating the remainder: 1234 % 10
will be 4.
So, 1234 / 10
is 123, so after x = x / 10
the value of x
will become 123.
Do it once more, x = x / 10
, and x
will become 12.
Once more, and it's 1.
Finally, since 1 / 10
is 0, after one more x = x / 10
it will become zero.
Let's solve the problem where you will need to use a while
loop (even though later we'll see how we can do it without any loops! – but for now, let's use it).
Write a function which returns number of digits in a number x
.
#include <stdio.h>
int number_of_digits(int x) {
/* your code goes here */
return 0;
}
int main() {
printf("Number of digits in 1 is %d\n", number_of_digits(1));
printf("Number of digits in 9 is %d\n", number_of_digits(9));
printf("Number of digits in 10 is %d\n", number_of_digits(10));
printf("Number of digits in 99 is %d\n", number_of_digits(99));
printf("Number of digits in 100 is %d\n", number_of_digits(100));
printf("Number of digits in 999 is %d\n", number_of_digits(999));
printf("Number of digits in 1000 is %d\n", number_of_digits(1000));
printf("Number of digits in 9999 is %d\n", number_of_digits(9999));
printf("Number of digits in 10000 is %d\n", number_of_digits(10000));
printf("Number of digits in 99999 is %d\n", number_of_digits(99999));
printf("Number of digits in 0 is %d\n", number_of_digits(0));
return 0;
}
If you feel stuck, go back to the previous page, read about the counters (c = c + 1
), and see if you could use one here!