C program to check whether a character is alphabet, digit or special character

Previous Program Next Program

Write a C program to check whether a given character is alphabet, digit or special character using if else. How to check if a character is alphabet, digits or any other special character using if else in C programming. Program to enter any character and check whether it is alphabet, digit or special character in C. Logic to check alphabets, digits or special characters in C program.

Example

Input

Input any character: 3

Output

3 is digit

Required knowledge

Basic programming, If else

Logic to check character is alphabet, digit or special character

This exercise is based on ladder if (or if else if). In previous exercises we learnt how to check alphabets. We are going to use the same logic to check digits and special characters.

Let us make a fresh definition again -

Let us implement the above definitions in our program.

Program to check alphabet, digit or special character

/**
 * C program to check alphabet, digit or special character
 */

#include <stdio.h>

int main()
{
    char ch;

    /* Read character from user */
    printf("Enter any character: ");
    scanf("%c", &ch);


    // Alphabet checking condition
    if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
    {
        printf("%c is ALPHABET.", ch);
    }
    else if(ch >= '0' && ch <= '9')
    {
        printf("%c is DIGIT.", ch);
    }
    else 
    {
        printf("%c is SPECIAL CHARACTER.", ch);
    }

    return 0;
} 

Note: You can also use ASCII character codes for checking alphabets, digits or special characters as shown in below program.

Program to check alphabet, digit or special character using ASCII value

/**
 * C program to check alphabet, digit or special character using ASCII value
 */

#include <stdio.h>

int main()
{
    char ch;

    /* Reads a character from user */
    printf("Enter any character: ");
    scanf("%c", &ch);


    if((ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90))
    {
        printf("%c is ALPHABET.", ch);
    }
    else if(ch >= 48 && ch <= 57)
    {
        printf("%c is DIGIT.", ch);
    }
    else
    {
        printf("%c is SPECIAL CHARACTER.", ch);
    }

    return 0;
} 
Output
Enter any character: a
a is ALPHABET.

Happy coding ;)

You may also like

Previous Program Next Program

Labels: , ,