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

Write a C program to input a character from user and check whether 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. Logic to check alphabet, digit or special character in C programming.

Example
Input

Input any character: 3

Output

3 is digit

Required knowledge

Basic C programming, Relational operators, Logical operators, If else

Logic to check alphabet, digit or special character

  • A character is alphabet if it in between a-z or A-Z.
  • A character is digit if it is in between 0-9.
  • A character is special symbol character if it neither alphabet nor digit.

Step by step descriptive logic to check alphabet, digit or special character.

  1. Input a character from user. Store it in some variable say ch.
  2. First check if character is alphabet or not. A character is alphabet if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')).
  3. Next, check condition for digits. A character is digit if(ch >= '0' && ch <= '9').
  4. Finally, if a character is neither alphabet nor digit, then character is a special character.

Let us implement the above logic in a C 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;

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


    /* Alphabet check */
    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;

    /* Input 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 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>