C Program to count the digits in a given number
Objective
Write a C program to count the number of digits in a given integer.
Algorithm / Approach
- Read an integer
nfrom the user. - Initialize a counter
dig = 0. - Start a
whileloop with the conditionn != 0. - Inside the loop, increment the digit counter:
dig++. - Remove the last digit of the number by dividing it by 10:
n = n / 10. - Once
nbecomes 0, print the counter.
main.c
#include<stdio.h>
int main( ) {
int n, dig=0;
printf("Enter Value for N : ");
scanf("%d", &n);
while(n!=0){
dig++;
n = n/10;
}
printf("TOTAL DIGITS : %d\n",dig);
printf("\n");
return 0;
}
Expected Output
Enter Value for N: 1232 TOTAL DIGITS : 4
Explanation of the Program
- A
whileloop is used when you do not know in advance exactly how many times the loop will run. You only know the condition when it should stop. - Because C uses integer division, dividing a number like 1232 by 10 results in 123 (the decimal is truncated). This effectively chops off the last digit. We keep chopping off digits and counting until nothing is left.
Complexity
Time Complexity
O(log₁₀ n) - The number of digits.
Space Complexity
O(1)