Check input character is alphabet, digit or special character in C

In this section, we will see how to check whether a given character is a number, alphabet, or special character in C. We can classify characters by checking their ASCII values against specific ranges.

The alphabets are from A – Z and a – z, numbers are from 0 – 9, and all other characters are considered special characters.

Syntax

if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
    // Alphabet
else if(ch >= '0' && ch <= '9')
    // Digit
else
    // Special character

Method 1: Using ASCII Range Comparison

This approach directly compares the character with ASCII ranges for alphabets and digits −

#include <stdio.h>

int main() {
    char ch;
    printf("Enter a character: ");
    scanf("%c", &ch);
    
    if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
        printf("This is an alphabet<br>");
    else if(ch >= '0' && ch <= '9')
        printf("This is a number<br>");
    else
        printf("This is a special character<br>");
    
    return 0;
}
Enter a character: F
This is an alphabet

Method 2: Using ctype.h Functions

The ctype.h library provides built-in functions for character classification −

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

int main() {
    char ch;
    printf("Enter a character: ");
    scanf("%c", &ch);
    
    if(isalpha(ch))
        printf("This is an alphabet<br>");
    else if(isdigit(ch))
        printf("This is a number<br>");
    else
        printf("This is a special character<br>");
    
    return 0;
}
Enter a character: 7
This is a number

Comparison

Method Pros Cons
ASCII Range No library needed, portable Manual range checking
ctype.h Functions More readable, handles locale Requires ctype.h library

Key Points

  • ASCII values for 'A'-'Z' are 65-90 and 'a'-'z' are 97-122
  • ASCII values for '0'-'9' are 48-57
  • The ctype.h functions are more portable across different character encodings

Conclusion

Character classification in C can be done using either ASCII range comparison or ctype.h functions. The ctype.h approach is generally preferred for its readability and locale support.

Updated on: 2026-03-15T10:34:53+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements