Let's try to write a program to solve the following problem:
You must enter a number (let it be less than 3,000,000) and determine the number of digits in it.
Solution idea
Let's start a counter of digits of a number. Initially, the counter is 0. 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 by 1.
As a result, after we cut off all the digits, in the counter we will get the number of digits in the number.
In another way, the algorithm can be formulated as follows:
UNTIL THE NUMBER IS NOT ZERO, DECREASE IT 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.
var n, count: integer;
begin
read(n);
count := 0;
while n <> 0 to begin
count += 1;
n := n div 10;
end;
writeln('Number - ', n, ' contains ', count, ' digits');
end.
You need to know this program by heart, because. on its basis, many other problems related to the calculation of numbers by digits are solved.