Let's try to write a program to solve the following problem: you need to enter a number and determine the number of digits in it.
Solution idea.
We just need to sequentially cut off the last digit from the number (this can be done by reducing the number by 10 times, using integer division by 10), and each time we need to increase the counter.
As a result, after we cut off all the numbers, the counter will store the number of digits in the number.
In another way, the algorithm can be formulated as follows: while the number is not equal to zero, decrease it by 10 times and increase the counter by 1.
number (n) |
counter |
123 |
0 |
12 |
1 |
1 |
2 |
0 |
3 |
The program will look like this:
...
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int count = 0;
while (n != 0)
{
count++;
n = n / 10;
}
}
You need to know and understand this program well, since many other tasks related to calculation by digits of a number.