Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to count the digits in a given number

C Code Example — Loop Programs

ADVERTISEMENT

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

  1. Read an integer n from the user.
  2. Initialize a counter dig = 0.
  3. Start a while loop with the condition n != 0.
  4. Inside the loop, increment the digit counter: dig++.
  5. Remove the last digit of the number by dividing it by 10: n = n / 10.
  6. Once n becomes 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 while loop 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)
ADVERTISEMENT