Count Digits of a Number in C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

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.

7. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?