Writing the program
In this step, we will write the C++ program to determine the number of digits present in a given number. Copy and paste the following code into your main.cpp
file:
// C++ program to count number of digits in a given number
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to count the number of digits in a given number ===== \n\n";
//variable declaration
int n, n1, num = 0;
//taking input from the command line (user)
cout << " Enter a positive integer : ";
cin >> n;
n1 = n; //storing the original number
//Logic to count the number of digits in a given number
while (n != 0)
{
n /= 10; //to get the number except the last digit.
num++; //when divided by 10, updated the count of the digits
}
cout << "\n\nThe number of digits in the entered number: " << n1 << " is " << num;
cout << "\n\n\n";
return 0;
}
In this program, we take input a positive integer from the user and store it in variables n
and n1
. We initialize num
to 0
which will store the count of the digits in the number. We then use a while loop to count the digits. In each iteration, we divide the number by 10, and increase the count of digit by 1. We continue this loop until the quotient becomes zero.
After the loop is finished, we display the value of num
which holds the count of the digits present in the entered number.