C Program to Count Number of Digits in an Integer

Created with Sketch.

C Program to Count Number of Digits in an Integer

In this programming tutorial, we will develop a simple C program to count the number of digits in an integer. The program will prompt the user to input an integer, and it will then calculate and display the count of digits in that number. We will provide a step-by-step explanation of the algorithm, present the C code implementation, and include examples of the program’s output.

Algorithm for Counting Digits in an Integer

  1. Input: Accept an integer from the user.
  2. Initialization: Set variables num to the input number and digitCount to 0.
  3. Loop:
    • In a loop, increment digitCount for each digit.
    • Update the value of num by removing its last digit using integer division (/).
    • Repeat the loop until num becomes 0.
  4. Output: Display the count of digits stored in the variable digitCount.

C Program for Counting Digits in an Integer

#include <stdio.h>

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

    // Input an integer from the user
    printf("Enter an integer: ");
    scanf("%d", &num);

    // Count the number of digits in the integer
    while (num != 0) {
        digitCount++;
        num /= 10;
    }

    // Display the count of digits
    printf("Number of digits: %d\n", digitCount);

    return 0;
}

Output Example

Example: Count Digits in an Integer (e.g., 45678)

Enter an integer: 45678
Number of digits: 5

Explanation

  1. Input: The user is prompted to enter an integer (e.g., 45678).
  2. Initialization: Variables num stores the input number, and digitCount is initialized to 0.
  3. Loop:
    • In each iteration of the loop, digitCount is incremented to count the digits.
    • The last digit is removed from num using integer division (/).
    • The loop continues until num becomes 0.
  4. Output: The count of digits is displayed.

Conclusion

This C program efficiently calculates the number of digits in an integer using a loop and basic arithmetic operations. The algorithm iterates through each digit, incrementing the count until there are no more digits left. Feel free to run the program with different numbers to observe the count of digits. If you have any questions or need further clarification, please don’t hesitate to ask!

Leave a Reply

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