Count number of digits in a given integer

To count the number of digits in a number we have to divide that number by 10 until it becomes 0 or less than 0. If you divide any number by 10 and store the result in an integer then it strips the last digit. So we have to apply the same logic here also.

Logic

After taking the input from the user, run one while loop that runs until the user given number becomes 0. Inside the loop for each iteration increase the counter variable by one and divide the user given number by 10 and store it in the same variable again.

Notice here we are using /= operator that performs division and stores the result in the same variable again.

Once the loop is over we have to print counter variable “count” containing the total number of digits.

Program

#include <stdio.h>

int main() {

    int num, temp;
    int product = 1;

    // Take input from user
    printf("Enter any number : ");
    scanf("%d", &num);

    temp = num;

    while(temp != 0) {

        product = product * (temp % 10);

        // Remove last digit from temp.
        temp = temp / 10;
    }

    printf("\nProduct of all digits in %d : %d", num, product);

    return 0;
}

Output

Enter any number : 123456
Total digits in 123456 : 6