Q:

C program to count number of digits in a number

belongs to collection: C Programming on Numbers

0

In this exercise, you learn how to write a C program to count number of digits in a number?. We will write a C program to input a number from the user and count number of digits in the given integer using a loop. How to find total digits in a given integer using loop in C programming? Write a C program to count digits in a given integer without using a loop. Also, we will see how to count the number of digits using a recursive function (recursion).

Input
Input num: 240627
 
 
Output
Number of digits: 6

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C Program to count total digits in a given integer using a loop:

#include <stdio.h>
int main()
{
    long long num;
    int count = 0;
    printf("Enter any number: ");
    scanf("%lld", &num);
    //Run loop till num > 0
    do
    {
        //Increment digit count
        count++;
        //Remove last digit of num
        num /= 10;
    }
    while(num != 0);
    printf("Digits count = %d", count);
    return 0;
}

Output:

Enter any number: 1234
Digits count = 4

 

Count number of digits in an integer without using the loop:

#include <stdio.h>
#include <math.h>
int main()
{
    int num;
    int count = 0;
    //Get input number from user
    printf("Enter any number: ");
    scanf("%d", &num);
    //check number should be positive
    if(num > 0)
    {
        //Calculate total digits
        count = (num == 0) ? 1  : (log10(num) + 1);
        printf("Total digits: %d", count);
    }
    else
    {
        printf("Enter positive number\n");
    }
    return 0;
}

Output:

Enter any number: 12345
Digits count = 5

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to reverse digits of an integer with ove... >>
<< C program to find the negative or positive number ...