Thursday, 21 August 2014

C Program to Count Number of Digits in a number


Here a C program to count number of digits in a number is given below.This program takes an integer from user and calculates the number of digits in that integer. For example: If user enters 2319, the output of program will be 4 because it contains 4 digits.

 C Program to Count Number of Digits in a number


#include <stdio.h>
int main()
{
  int n,count=0;
  printf("Enter an integer: ");
  scanf("%d", &n);
  while(n!=0)
  {
      n/=10;             /* n=n/10 */
      ++count;
  }
  printf("Number of digits: %d",count);
}
Output
Enter an integer: 34523
Number of digits: 5
Explanation
This program takes an integer from user and stores that number in variable n. Suppose, user entered 34523. Then, while loop is executed because n!=0
will be true in first iteration. The codes inside while loop will be executed. After first iteration, value of n will be 3452 and count will be 1. Similarly, in second iteration n will be equal to 345 and count will be equal to 2. This process goes on and after fourth iteration, n will be equal to 3 and count will be equal to 4. Then, in next iteration n will be equal to 0 and count will be equal to 5 and program will be terminated as n!=0
becomes false.