Count the number of digits in C

Count the number of digits in C

Count the number of digits in C

Now, we will look at how to count the number of digits in an integer. This integer is nothing but the number entered by the user.

First, we will calculate count the number of digits using for or while loop.

Approach:

  • Firstly, the number will be entered by the user. Suppose we declare the variable ‘n’ and stores the integer value in the ‘n’ variable.
  • We will create a while loop that iterates until the value of ‘n’ is not equal to zero.
  • Suppose the value of ‘n’ is 123.
  • When the first iteration executes, the value of ‘n’ will be 123, and the value of count will be incremented to 1.
  • When the second iteration executes, the value of ‘n’ will be 12, and the value of count will be incremented to 2.
  • When the third iteration executes, the value of ‘n’ will be 1, and the value of count will be incremented to 3.
  • After the completion of the third iteration, the value of ‘n’ becomes 0, and loop is terminated as it does not satisfy the condition (n!=0).

Let’s create a program which will implement the above approach.

#include <stdio.h>

int main()

{

int n;  // variable declaration

int count=0;   // variable declaration

printf(“Enter a number”);

scanf(“%d”,&n);

while(n!=0)

{

n=n/10;

count++;

}

 

printf(“\nThe number of digits in an integer is : %d”,count);

return 0;

}

Output

Count the number of digits in C

Now, we will see how to count the number of digits without using a loop.

Related Post:

Features of C Programming Language

Variables in C

Data Types in C

Keywords in C

C Operators

Comments in C

Escape Sequence in C

C Functions

Storage Classes in C

Dynamic memory allocation in C

Factorial Program in C

Leap year program in C

Fibonacci Series in C

Prime Number program in C

Palindrome program in C

Sum of digits program in C

Escape Sequence in C

ASCII value in C

Difference Between Type Casting and Type Conversion in C

Difference Between Variables and Constants

Matrix multiplication in C

C Program to generate Fibonacci Triangle

C Program to print “hello” without semicolon

C Program to swap two numbers without third variable

C Program to reverse number

Count the number of digits in C

Tokens in C

C Identifiers

C Strings

Compile time vs Runtime in C

C break statement

C goto statement

Type Casting in C

C String Functions

C Pointers

Dangling Pointers in C

void pointer in C

Pointer to Pointer in C

Recursion in C

Call by value and Call by reference in C

File Handling in C

C fprintf() and fscanf()

C fputc() and fgetc()

C fputs() and fgets()

C fseek() function

Constant Pointers in C