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
- Read an integer
n. - Initialize a
countto 0. - Start a
while (n > 0)loop. - Inside the loop, divide the number by 10 (
n = n / 10) to strip away the last digit. - Increment the
countby 1. - 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
whileloop is used here instead of aforloop 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)