fastread homefastrread library fastread menu

C : Count Number of Digits of an Integer

Tutorial by:Manisha Dubey      Date: 2016-06-17 03:37:05

❰ Previous Next ❱

Example to count the number of digits of an integer entered by the user. The while loop is used to solve this program.

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

Example #1: Program to Count Number of Digits in an Integer

#include <stdio.h>
int main()
{
    long long n;
    int count=0;

    printf("Enter an integer: ");
    scanf("%lld", &n);

    while(n!=0)
    {
        n /= 10;             // n = n/10
        ++count;
    }

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

Output

Enter an integer: 3452
Number of digits: 4

The integer entered by the user is stored in variable n. Then the while loop is iterated until the test expression n != 0 is evaluated to 0 (false).

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

❰ Previous Next ❱


C

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website