C Example for Beginners: C Program to Count Number of Digits in an Integer

(C programming Example for Beginners)

C Program to Count Number of Digits in an Integer

In this example, you will learn to count the number of digits in an integer entered by the user.


This program takes an integer from the user and calculates the number of digits. For example: If the user enters 2319, the output of the program will be 4.


Program to Count the Number of Digits


#include <stdio.h>
int main(){
    long long n;
    int count = 0;
    printf("Enter an integer: ");
    scanf("%lld", &n);
 
    // iterate until n becomes 0
    // remove last digit from n in each iteration
    // increase count by 1 in each iteration
    while (n != 0) {
        n /= 10;     // n = n/10
        ++count;
    }

    printf("Number of digits: %d", count);
}

Output

Enter an integer: 3452
Number of digits: 4

  • After the first iteration, the value of n will be 345 and the count is incremented to 1.
  • After the second iteration, the value of n will be 34 and the count is incremented to 2.
  • After the third iteration, the value of n will be 3 and the count is incremented to 3.
  • After the fourth iteration, the value of n will be 0 and the count is incremented to 4.
  • Then the test expression of the loop is evaluated to false and the loop terminates.

 

C Example for Beginners: C Program to Count Number of Digits in an Integer

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.