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
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.
- Input a character from user. Store it in some variable say ch.
- First check if character is alphabet or not. A character is alphabet
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
. - Next, check condition for digits. A character is digit
if(ch >= '0' && ch <= '9')
. - 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 😉