Albiorn Gjuzi
PRO
3 months ago
Albiorncountry asked

How do I check with an if condition whether a value is a character or a number?

Kelish Rai
Expert
2 months ago
Kelish Rai answered

Here's how you can check with an if...else statement whether a value is a character or not:

if ((alphabet >= 'a' && alphabet <= 'z') || (alphabet >= 'A' && alphabet <= 'Z')) {
    printf("Alphabet");
} else {
    printf("Not an Alphabet");
}

Here,

  • The condition alphabet >= 'a' && alphabet <= 'z' checks if the character is a lowercase letter (from a to z).

  • The condition alphabet >= 'A' && alphabet <= 'Z' checks if it’s an uppercase letter (from A to Z).

  • The || (OR) operator ensures that if either condition is true, the program will print "Alphabet".

  • If neither condition is true, the program prints "Not an Alphabet" in the else block.

To check if it’s a number:

If you want to check if the value is a number (digit 0-9), you can extend the logic like this:

if ((alphabet >= 'a' && alphabet <= 'z') || (alphabet >= 'A' && alphabet <= 'Z')) {
    printf("Alphabet");
} else if (alphabet >= '0' && alphabet <= '9') {
    printf("Number");
} else {
    printf("Special Character");
}

This version will now differentiate between alphabets, numbers, and special characters.

C
This question was asked as part of the Practice: C Programming course.