If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, you can use a while loop to count the number of digits in a given integer. The basic idea is to repeatedly divide the number by 10 until it becomes zero, and count the number of divisions.
Here's an example of C code that counts the number of digits in a given number:
Copy code
#include <stdio.h>
int main() {
int n, count = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
while (n != 0) {
n /= 10;
++count;
}
printf("The number of digits in the entered integer is %d.\n", count);
return 0;
}
This code prompts the user to enter a positive integer, and then uses a while loop to repeatedly divide the number by 10 until it becomes zero. It uses a variable 'count' to keep track of the number of divisions. Within the while loop, it uses the shorthand operator /=
which divides the number by 10 and assigns the result to the same variable. And increments the count variable. After the while loop, it prints the number of digits in the entered integer which is stored in the count variable. It's also possible to use a for loop and modulus operator to get the number of digits of an integer.
Comments: 0