C Program to count number of digits in a number

Category: C ProgramTags: cprogram loops

Write a C Program to count the number of digits in a number using a loop and without using a loop. How to find the number of digits in a number using a loop and without using a loop. Logic to find the number of digits in a number using while and without using loop by log10.

C Program to count number of digits in a number using while loop

#include <stdio.h>

void main()
{
    int num, count = 0;
    printf("Enter number: ");
    scanf("%d", &num);

    while(num > 0)
    {
        num = num / 10;
        count++;
    }

    printf("Number of digits: %d", count);
}

C Program to count the number of digits in a number without using loop - by log10

#include <stdio.h>

void main()
{
    int num, count;
    printf("Enter number: ");
    scanf("%d", &num);

    if (num == 0)
        count = 1;
    else
        count = log10(num) + 1;

    printf("Number of digits: %d", count);
}

Output

Output

Enter number: 1234
Number of digits: 4