C program for testing the character type

In C programming, the ctype.h library provides predefined functions for analyzing and converting character types. These functions are essential for validating user input and performing character-based operations.

Syntax

#include <ctype.h>

int isalpha(int c);
int isdigit(int c);
int isspace(int c);
int ispunct(int c);
int islower(int c);
int isupper(int c);
int isalnum(int c);
int tolower(int c);
int toupper(int c);

Analysis Functions

The character analysis functions are listed below −

Function Checks whether entered character is
isalpha An alphabet or not
isdigit A digit or not
isspace A space, a newline or tab
ispunct A special symbol or not
islower A lower case letter of alphabet
isupper An upper case letter of alphabet
isalnum An alphabet/digit or not

Converting Functions

The converting functions are listed below −

Function Conversion
tolower() Converts an upper case alphabet to lower case
toupper() Converts a lower case alphabet to upper case

Example

Following is the C program for character analysis and conversion functions which are used to test the character type −

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

int main() {
    char character;
    printf("Press any key digit or alphabet<br>");
    character = getchar();
    
    if (isalpha(character) > 0)
        printf("The character is a letter.");
    else
        if (isdigit(character) > 0)
            printf("The character is a digit.");
        else
            printf("The character is not alphanumeric.");
    
    return 0;
}
Press any key digit or alphabet
3
The character is a digit.

Complete Character Testing Program

Here's a more comprehensive example that demonstrates multiple character testing functions −

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

int main() {
    char ch = 'A';
    
    printf("Testing character: %c<br>", ch);
    printf("isalpha: %d<br>", isalpha(ch));
    printf("isupper: %d<br>", isupper(ch));
    printf("islower: %d<br>", islower(ch));
    printf("tolower: %c<br>", tolower(ch));
    
    ch = '5';
    printf("\nTesting character: %c<br>", ch);
    printf("isdigit: %d<br>", isdigit(ch));
    printf("isalnum: %d<br>", isalnum(ch));
    
    return 0;
}
Testing character: A
isalpha: 1
isupper: 1
islower: 0
tolower: a

Testing character: 5
isdigit: 1
isalnum: 1

Conclusion

The ctype.h library functions provide efficient ways to test character types and perform case conversions. These functions return non-zero values for true conditions and zero for false, making them useful in conditional statements for character validation.

Updated on: 2026-03-15T14:06:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements