can someone explain me this program?

This program tells us the number of digits we enter. For example;
1. If we enter 1, the program will display "You entered 1 digit(s)"
2. If we enter 51, the program will display "You entered 2 digit(s)"
3. If we enter 846, the program will display "You entered 3 digit(s)"
4. If we enter 2053, the program will display "You entered 4 digit(s)"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
int main ()
{
	int num=0,counter=0;
	
	cout<<"Please enter a number : ";
 	cin>>num;

	while(num>0)
	{
		num=num/10;
		counter++;
	}
	
	cout<<"You entered "<<counter<<" digit(s)";

	return 0;
		
}


What i can't understand is the WHILE LOOP. Why is the entered number being divided by 10? Please explain that what is happening in the WHILE LOOP.
Last edited on
This is base on integer division. There is no position after the decimal point.

Hence 2053 -> num=num/10; -> 205 -> num=num/10; -> 20 -> etc. until 0

This way you can count the digits.
Topic archived. No new replies allowed.