Counting The Number Of Digits In An Integer In C

This tutorial will teach you how to write a C program that counts the number of digits in an integer. For example, number 3456 has four digits, number 555 has three digits, and so on.

Count the number of digits in an integer with this program

This program’s logic is straightforward. The user input is recorded and saved in the form of a variable number. The value of number was then copied to another temporary variable temp. This is due to the fact that we need to perform some arithmetic operations on the temp.
In the following step, we divide the number by 10 and store the quotient value in the number itself (temp /=10 is the same as temp = temp/10). The goal is to remove the last digit from the number and count the digit that was removed by increasing the counter count by one.
The loop continues until all of the digits have been removed and the number (temp) becomes zero; at this point, 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;
  } while (temp != 0);

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

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button