Rewrite C Function: isdigit

Last Updated : 10 July, 2022 · 2 min read

articles banner image

In this article we will overview isdigit function and it's workings in C programming language. With this text we aim to satisfy the following three objectives:

Structure of isdigit:

Declaration: int isdigit(int c);

Return: non-zero value if int c has a digit ASCII value. Otherwise, 0.

Parameter list:
(int c) - the character that is checked to determine the return value.

Header file: <ctype.h>.

1. So, what is isdigit in C?

The isdigit function evaluates an int value and determines if the value is a digit (0-9).

If the argument is, in fact, a digit, the function isdigit returns a non-zero value.

If the argument is not a digit, however, 0 is returned.

In order to use this C library function we have to include <ctype.h> header file into our program (e.g. #include <ctype.h>).

Example 1: Usage of isdigit.

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

int main( void )
{
    
printf ( "%d\n", isdigit ( 'a' ));
    
printf ( "%d\n", isdigit ( '1' ));
    
return ( 0 );
}

Possible output:

0
1

2. And how to rewrite the isdigit function in C?

Consider the lines of code below for a second:

Example 2: Rewritten isdigit function in C.

int our_isdigit ( int c )
{
    
if (c >= 48 && c <= 57 )
        
return ( 1 );
    
return ( 0 );
}

The our_isdigit function above takes one parameter. Since this parameter c is of int type, arguments of char type (when sent as arguments to this function) get implicitly typecasted to an according numeric values, as shown in the ASCII table below.

ASCII table of numeric values:

int char
0 '48'
1 '49'
2 '50'
3 '51'
4 '52'
5 '53'
6 '54'
7 '55'
8 '56'
9 '57'

Then it is checked if the received value of c is in the range of [48,57] (On line 3). If this condition is true, it means that the value is a digit and 1 is returned. Otherwise 0 is returned, indicating that the value c is not a digit.

3. Quiz of isdigit knowledge

Quiz : Rewritten isdigit function in C

1What is return value of isdigit('a')?

2In which C library is isdigit function defined?

3What is return value of isdigit(97)?

quiz completed!

Congrats!

Feel free to share your achievement below!