Quantcast
Channel: Codeforwin
Viewing all articles
Browse latest Browse all 132

C program to count number of digits in an integer

$
0
0
Write a C program to read an integer from user and count total number of digits the integer contains. 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 using C program.

Example:
Input num: 35419
Output digits: 5

Required knowledge

Basic C programming, Loop

Logic to count number of digits in an integer

There are plenty of ways through which you can count the number of digits in a given integer. Here we will be looking two of the methods through which we can find the number of digits in an integer.
First is the easiest method to count number of digits in an integer.
  1. Initialize a variable count to 0.
  2. Increment count by 1 if num > 0 (where num is the number whose digits count is to be found).
  3. Remove the last digit from the number as it isn't needed anymore. Hence divide the number by 10 i.e num = num / 10.
  4. If number is greater than 0 then repeat steps 2-4.


Program to count number of digits in an integer


/**
* 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; // num = num / 10
}

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

return 0;
}


Now, lets take a look to the second method of finding total number of digits in a given integer using mathematical approach. This method is more simpler and shorter to use. Before using this method you must have a good knowledge of logarithms.


Program to find number of digits in an integer


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

#include <stdio.h>
#include <math.h>

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 ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles