Cover Image for Count the number of digits in C
73 views

Count the number of digits in C

You can count the number of digits in a given integer in C by repeatedly dividing the number by 10 until it becomes zero, incrementing a counter with each division. Here’s a C program to count the number of digits:

C
#include <stdio.h>

int main() {
    int num, count = 0;

    printf("Enter an integer: ");
    scanf("%d", &num);

    // Handle the case of negative numbers
    if (num < 0) {
        num = -num;
    }

    // Count the number of digits
    do {
        num /= 10;
        count++;
    } while (num != 0);

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

    return 0;
}

In this program:

  1. We input an integer from the user.
  2. If the input number is negative, we make it positive by taking its absolute value (-num) because the number of digits in a negative number is the same as in its positive counterpart.
  3. We then enter a loop that repeatedly divides the number by 10 and increments the count variable until the number becomes zero.
  4. After the loop, we print the value of the count variable, which represents the number of digits in the input integer.

Compile and run the program, and it will count and display the number of digits in the entered integer.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS