C program to count number of digits in an integer

Previous Program Next Program

Write a C program to count number of digits in an integer. How to find total number of digits in a given integer using loop in C programming. Logic to count number of digits in a given integer without using loop in C program.

Example

Input

Input num: 35419

Output

Number of digits: 5

Required knowledge

Basic C programming, Loop

Logic to count number of digits in an integer

There are various logic to count number of digits in an integer. Today I will explain two logic to count number of digits, using loop and without using loop. First logic is the easiest and is the common to think. It uses loop to count number of digits.

Logic to count number of digits in given integer using loop.

  1. Read a number from user. Store it in some variable say num.
  2. Initialize another variable with 0 say digit = 0.
  3. Copy the value of num to some temporary variable say temp = num.
  4. If temp > 0 then increment the value of count by 1 i.e. count = count + 1.
  5. Divide temp by 10 to remove last digit i.e. temp = temp / 10.
  6. Repeat step 4-5 till temp > 0 or temp != 0.

Program to count number of digits in an integer using loop

/**
 * C program to count number of digits in an integer
 */

#include <stdio.h>

int main()
{
    long long num;
    int count = 0;

    printf("Enter any number: ");
    scanf("%lld", &num);

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

    printf("Total digits: %d", count);

    return 0;
}

Logic to count number of digits without using loop

As I talked earlier let us now move on to our second logic to compute number of digits. It uses mathematical approach. It is simpler and shorter to use. Before I formally discuss this method you must have a good knowledge of logarithms.

For this logic we will make use of log10(x) function. It returns the logarithm of x to the base 10. It basically returns total number of digits - 1. Hence to get total number of digit you can use log10(x) + 1. Let us now implement this.

Program to count number of digits without using loop

/**
 * C program to count number of digits in an integer without loop
 */

#include <stdio.h>
#include <math.h> //Used for log10()

int main()
{
    long long num;
    int count = 0;

    printf("Enter any number: ");
    scanf("%lld", &num);

    count = log10(num) + 1;

    printf("Total digits: %d", count);

    return 0;
}
Output
Enter any number: 123456789
Total digits: 9

Happy coding ;)

You may also like

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment