BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C Program to Count Number of Digits in an Integer

Last Updated: July 15, 2022 by Chaitanya Singh | Filed Under: C Programs

In this tutorial, you will learn how to write a C program to count number of digits in an integer. For example number 3456 has 4 digits, number 555 has 3 digits etc.

Program to count number of digits in an integer

The logic used in this program is pretty simple. The user input is captured and stored in a variable number. We then copied the value of number to another temporary variable temp. This is because, we need to perform some arithmetic operations on the temp.

In the next step, inside do-while loop we are dividing the number by 10 and storing the quotient value into the number itself (temp /=10 is same as temp = temp/10). The purpose of doing this is to remove the last digit from the number and count the removed digit by increasing the counter count by 1.

The loop keeps repeating until all the digits are removed and the number (temp) becomes zero, at this point the the count variable has counted the number of digits in the number.

#include <stdio.h>
int main() {
  long number, temp;
  int count = 0;
  printf("Enter an integer: ");
  scanf("%ld", &number);

  //copying the number in a temporary variable to perform
  //calculations on it.
  temp = number;

  //Here we are counting the digits of the input
  //number. At every loop iteration, we are increasing
  //the counter by 1 and removing the last digit from the
  //number by dividing it by 10. This goes on until number
  //becomes 0.
  do {
    temp /= 10;
    ++count;
  } while (temp != 0);

  printf("Number of digits in the number %ld is: %d", number,count);
}

Output:
C Program to Count Number of Digits in an Integer

Related C Examples:

  • C Program to check whether a number is prime or not
  • C Program to display characters from ‘A’ to ‘Z’
  • C Program to swap two numbers
  • C Program to convert decimal number to binary number
❮ C TutorialC Programs ❯

Top Related Articles:

  1. C Program to display factors of a number
  2. C Program to check abundant number
  3. C Program to find Palindrome numbers in a given range
  4. C Program to find the Size of int, float, double and char
  5. C Program to find factorial of a number using Recursion

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap