C Program to Count Number of Digits in an Integer

1. Introduction

Counting the number of digits in an integer is a foundational programming exercise. The process involves iterating through each digit of the number by repeatedly dividing it by 10 until the number is reduced to zero. In this tutorial, we will walk through a C program that achieves this.

2. Program Overview

1. Prompt the user to input an integer.

2. Initialize a count variable to zero.

3. Use a loop to repeatedly divide the number by 10, increasing the count at each iteration, until the number becomes zero.

4. Display the count, which represents the number of digits.

3. Code Program

#include <stdio.h>

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

    // Prompt user for input
    printf("Enter an integer: ");
    scanf("%d", &num);

    // Check for the special case when the number is 0
    if(num == 0) {
        count = 1;
    } else {
        // Count the number of digits
        while(num != 0) {
            count++;       // Increase the count
            num /= 10;     // Reduce the number
        }
    }

    printf("The number has %d digits.\n", count);
    return 0;
}

Output:

Enter an integer: 12345
The number has 5 digits.

4. Step By Step Explanation

1. We begin by prompting the user to input an integer.

2. We check if the entered number is 0 because 0 is a special case where the number of digits is 1.

3. If the number is not 0, we enter a loop where:

- We increment our count.

- We divide the number by 10, effectively removing its last digit.

4. This loop continues until the number becomes zero.

5. Finally, we print out the count of digits.

Comments