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

Write a C program to check whether a 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.

Example:
Input any character: 3
Output: 3 is a digit.

Required knowledge

Basic programming, If else

Logic to check if a character is alphabet, digit or special character

Till now we already know how to check alphabets. We would be using same logic here also to check for digits or special characters. A character is digit if it is in range of 0-9 ASCII value 48-57. And a character is a special symbol character if it neither an alphabet nor a digit.

Program to check alphabet, digit or special character

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

#include <stdio.h>

int main()
{
    char ch;

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


    /* Checks if it is an alphabet */
    if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
    {
        printf("%c is ALPHABET.\n", ch);
    }
    else if(ch >= '0' && ch <= '9')
    {
        printf("%c is DIGIT.\n", ch);
    }
    else 
    {
        printf("%c is SPECIAL CHARACTER.\n", ch);
    }

    return 0;
} 


Note: You can also use ASCII character codes for checking alphabets, digits or special characters.


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.\n", ch);
    }
    else if(ch >= 48 && ch <= 57)
    {
        printf("%c is DIGIT.\n", ch);
    }
    else
    {
        printf("%c is SPECIAL CHARACTER.\n", ch);
    }

    return 0;
} 


Output
Enter any character: a
a is ALPHABET.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment