Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to count the digits in a given number

C++ Code Example — Loop Programs

ADVERTISEMENT

WAP to count the digits in a given number

Objective

Write a C++ program to count the number of digits in a given number.

Algorithm / Approach

  1. Read an integer n.
  2. Initialize a count to 0.
  3. Start a while (n > 0) loop.
  4. Inside the loop, divide the number by 10 (n = n / 10) to strip away the last digit.
  5. Increment the count by 1.
  6. Print the final count.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int n;
 cout<<"Enter the Value for N: ";
 cin>>n;
 int count = 0;
 while(n>0) {
  n = n/10;
  count++;
 }
 cout<<"Total Digits = "<< count;

return 0;
}

Expected Output

Enter the Value for N: 12345
Total Digits = 5

Explanation of the Program

  • The while loop is used here instead of a for loop because we don't know exactly how many digits the number has beforehand.
  • In C++, dividing an integer by 10 performs integer division, which effectively chops off the last digit. We keep chopping digits off and counting them until the number becomes 0.

Complexity

Time Complexity O(log₁₀ n)
Space Complexity O(1)
ADVERTISEMENT