C library function isdigit( )

In this tutorial, you will learn about C library function isdigit() which is a character handling function used to check whether the argument is a digit(0-9) or not. This function returns true(1) if the argument is digit else it returns 0.

C library function isdigit( )

We should include ctype.h header to use isdigit( ) function.

#include <ctype.h>

C library function isdigit( ): Function prototype


int isdigit( int ch);

This function checks whether its argument is a digit (0-9).

It returns a true value if the argument is a digit (0-9) and 0 otherwise.

Example: Demonstration of isdigit( ) function

#include <stdio.h>
#include <ctype.h>

int main()
{
  printf("Demonstration of isdigit( ):\n");
  printf("\n%s%s", isdigit('4') ? "4 is a " : "4 is not a ", "digit");
  printf("\n%s%s", isdigit('a') ? "a is a " : "a is not a ", "digit");
  printf("\n%s%s", isdigit('$') ? "$ is a " : "$ is not a ", "digit");

  return 0;

}

Output

Demonstration of isdigit( ):

4 is a digit
a is not a digit
$ is not a digit

[adsense1]

Explanation

In the above program, isdigit the standard library function is used to determine whether the argument is a digit or not.

Conditional operator ?: also know as a ternary operator is used to determine which string should be printed i.e. “is a” or “is not a”.

This can be simply achieved by using if...else condition which is shown below

#include <stdio.h>
#include <ctype.h>

int main()
{
   printf("Demonstration of isdigit( ):\n");

   if( isdigit('4') == 0)
     printf("\n4 is not a digit");
   else
     printf("\n4 is a digit");

   if( isdigit('a') == 0)
     printf("\na is not a digit");
   else
     printf("\na is a digit");

   if( isdigit('$') == 0)
     printf("\n$ is not a digit");
   else
     printf("\n$ is a digit");

   return 0;
}

Output

Demonstration of isdigit( ):

4 is a digit
a is not a digit
$ is not a digit

Now, note the difference between conditional operator (?:) and if...else condition. Here, we have used if...else for selecting between two strings.