Module: (Java) Loop statement with condition - while


Problem

6/21

Numbers digits

Theory Click to read/hide

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


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, in the counter we get 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, reduce it by 10 times and increase the counter by 1.

число (n) счетчик
123 0
12 1
1 2
0 3
The program will look as follows.
#include<iostream>
using namespace std;
main()
{
int n, count;
cin >> n;
count = 0;
while (n != 0) 
  {
  count ++;
  n = n / 10;
  }
cout << "Number - " <<n<< " contains " << count << " digits";  
}
This program needs to know by heart, because on its basis, many other problems are solved related to the calculation of numbers by digits.

Problem

Run the program.

Look at the result of her work.
Is everything normal in the output phrase.
Think about how to fix this defect.