#include <stdio.h>

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

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

    // Handle the case for 0 explicitly
    if (number == 0) {
        count = 1;
    } else {
        // Check if the number is negative
        if (number < 0) {
            number = -number;  // Convert to positive
        }

        // Count digits
        while (number != 0) {
            number /= 10;  // Remove the last digit
            count++;       // Increment count
        }
    }

    // Display the result
    printf("Number of digits: %d\n", count);
    return 0;
}

Explanation:

Include the Standard I/O Library:

  • #include <stdio.h>: This line includes the standard input-output library necessary for using printf and scanf functions.

Main Function:

  • int main(): This is the entry point of the program. The program starts executing from this function.

Variable Declaration:

  • int number, count = 0;: We declare two integer variables:
    • number will hold the user input.
    • count will keep track of the number of digits in the integer.

User Input:

  • printf("Enter an integer: ");: This line prompts the user to enter an integer.
  • scanf("%d", &number);: This reads the integer input from the user and stores it in the number variable.

Handling the Zero Case:

  • The condition if (number == 0) checks if the input is zero. Since zero has one digit, we set count to 1 in this case.

Handling Negative Numbers:

  • The condition if (number < 0) checks if the number is negative. If it is, we convert it to positive by multiplying it by -1 (or simply using number = -number;). This is important because the number of digits is the same for both positive and negative integers.

Counting Digits:

  • The while (number != 0) loop runs as long as number is not zero. Inside the loop:
    • number /= 10;: This line removes the last digit from the number by performing integer division. For example, if number is 123, it becomes 12.
    • count++;: Each time we remove a digit, we increment the count variable.

Display the Result:

  • printf("Number of digits: %d\n", count);: Finally, we print the number of digits counted.

Return Statement:

  • return 0;: This indicates that the program has executed successfully.

OUTPUT

Enter an integer: 12345

Number of digits: 5

Leave a Reply

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

Verified by MonsterInsights