Implementation of countDigits(int) Function
To implement a countDigits(int) function in C that counts the number of digits in an integer, you can use a simple iterative approach. Here's an example of how to implement the countDigits()
function:
Example:
#include <stdio.h>
// Function to count the number of digits in an integer
int countDigits(int num) {
int count = 0;
// Handle the case of 0 separately
if (num == 0) {
return 1;
}
while (num != 0) {
// Increment the count for each digit
count++;
num /= 10;
}
return count;
}
int main() {
int number = 12345;
int digitCount = countDigits(number);
printf("Number of digits in %d: %d\n", number, digitCount);
return 0;
}
In this example:
- The
countDigits()
function takes an integer num
as its parameter and initializes a variable count
to 0.
- It handles the case of
num
being 0 separately because 0 has one digit.
- Inside the
while
loop, the function repeatedly divides num
by 10 and increments the count
variable for each digit until num
becomes 0.
- The function returns the
count
as the number of digits in the integer.
- In the
main()
function, a number (12345 in this case) is passed to the countDigits()
function, and the digit count is stored in the digitCount
variable.
- Finally, the program prints the number of digits in the original number.
Output:
Number of digits in 12345: 5
You can use this countDigits()
function to count the number of digits in any integer by passing it as an argument to the function.