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
- Input: Accept an integer from the user.
- Initialization: Set variables
num
to the input number anddigitCount
to 0. - 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.
- In a loop, increment
- 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
- Input: The user is prompted to enter an integer (e.g., 45678).
- Initialization: Variables
num
stores the input number, anddigitCount
is initialized to 0. - 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.
- In each iteration of the loop,
- 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!