Rewrite C Function: isalpha

Last Updated : 10 July, 2022 · 2 min read

articles banner image

Today we are going to provide you with a detailed overview of the isalpha function in the C programming language. For the reader's convenience, this tutorial is split up into three following parts:

Structure of isalpha:

Declaration: int isalpha(int c);

Return: non-zero value if int c is an alphabetic 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 the isalpha function in C?

This function in C language checks if the passed char value is in the alphabet (uppercase or lowercase) or not, and returns appropriate value of type int indicating the result.

If the argument is not in an alphabet , function isalpha returns 0.

If the argument is in an alphabet, a non-zero value is returned.

The isalpha function is defined in the standard C library - <ctype.h>. For this function to be usable, we have to include this library in our program (e.g. #include <ctype.h> ).

Example 1: the isalpha function in C.

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

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

Possible output:

0
1

2. How to rewrite the isalpha function in C?

Consider the code snippet below for a second:

Example 2: rewritten isalpha function in C.

int our_isalpha ( int c )
{
    
if ( ( c >= 65 && c <= 90 ) || ( c >= 97 && c <= 122 ) )
        
return ( 1 );
    
return ( 0 );
}

The our_isalpha function above takes one parameter. This parameter gets implicitly typecasted to an according numerical value.

Then it is checked if the received value of c is in the range of [65, 90] or in the range of [97,122] (On line 3). If this condition is true, it means that the value is in the uppercase or lowercase alphabet and 1 is returned. Otherwise 0 is returned, indicating that the value c is not in any alphabet, neither in lowercase nor in uppercase.

Example 3: Test of the rewritten isalpha function in C.

# include <stdio.h>

int our_isalpha ( int c )
{
    
if ( ( c >= 65 && c <= 90 ) || ( c >= 97 && c <= 122 ) )
        
return ( 1 );
    
return ( 0 );
}

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

Possible output:

0
1

Feel free to run the given test to see if we have successfully rewritten the isalpha function in the C programming language.

Note: giving 'a' - 1 as an argument (on line 10) returns 0, because 'a' - 1 is equal to 64 and 64 is outside the alphabet ranges.

3. Quiz of the reader's knowledge

Quiz : Rewrite C Function

1What is the return value of isalpha(55)?

2What is the return value of isalpha('b' - 1)?

3In which library is isalpha defined?

quiz completed!

Congrats!

Feel free to share your achievement below!