Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to check the type of character entered
In C programming, determining the type of a character involves checking whether the entered character is an uppercase letter, lowercase letter, digit, or special character. This can be accomplished by examining the ASCII value of the character and comparing it against specific ranges.
Syntax
if (character >= 'A' && character <= 'Z')
/* uppercase letter */
else if (character >= 'a' && character <= 'z')
/* lowercase letter */
else if (character >= '0' && character <= '9')
/* digit */
else
/* special character */
Algorithm
The algorithm to identify character type follows these steps −
- Step 1 − Read the input character from user
- Step 2 − Check if ASCII value is between 65-90 (A-Z) for uppercase
- Step 3 − Check if ASCII value is between 97-122 (a-z) for lowercase
- Step 4 − Check if ASCII value is between 48-57 (0-9) for digits
- Step 5 − All other characters are special characters
Method 1: Using ASCII Values
This method directly compares the ASCII values of characters −
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (ch >= 65 && ch <= 90) {
printf("'%c' is an Upper Case Letter<br>", ch);
}
else if (ch >= 97 && ch <= 122) {
printf("'%c' is a Lower Case Letter<br>", ch);
}
else if (ch >= 48 && ch <= 57) {
printf("'%c' is a Digit<br>", ch);
}
else {
printf("'%c' is a Special Character<br>", ch);
}
return 0;
}
Enter a character: H 'H' is an Upper Case Letter
Method 2: Using Character Literals
This approach uses character literals for better readability −
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (ch >= 'A' && ch <= 'Z') {
printf("'%c' is an Uppercase Letter<br>", ch);
}
else if (ch >= 'a' && ch <= 'z') {
printf("'%c' is a Lowercase Letter<br>", ch);
}
else if (ch >= '0' && ch <= '9') {
printf("'%c' is a Digit<br>", ch);
}
else {
printf("'%c' is a Special Character<br>", ch);
}
return 0;
}
Enter a character: 5 '5' is a Digit
Key Points
- ASCII values: A-Z (65-90), a-z (97-122), 0-9 (48-57)
- Character literals ('A', 'a', '0') are more readable than ASCII values
- Both methods produce identical results
- Special characters include symbols, punctuation, and whitespace
Conclusion
Character type checking in C is straightforward using conditional statements with ASCII value ranges. The character literal approach is preferred for better code readability and maintainability.
Advertisements
