C program to check whether a character is alphabet or not

Write a C program to check whether a character is alphabet or not using if else. How to check whether a character is alphabet or not in C programming. Program to check character is alphabet or not in C.

Example:
Input character: a
Output: 'a' is alphabet

Required knowledge

Basic C programming, Use of relational operator, If else

Logic to check alphabets

In C programming we can easily perform relational operations > < >= <= == != on characters, since they are internally represented as an integer known as ASCII values. Hence, in order to check if a character is alphabet we just need to check the range of character i.e. it must lie between a-z or A-Z (Note: a and A both are different and have different ASCII values). To check a character is in range we can use relational operator along with the logical AND && operator.

Program to check alphabets

/**
 * C program to check whether a character is alphabet or not
 */

#include <stdio.h>

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

    if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
    {
        printf("Character is an ALPHABET.\n");
    }
    else
    {
        printf("Character is NOT ALPHABET.\n");
    }

    return 0;
} 


Note: You can also use ASCII values for checking characters. ASCII value of a = 97 z = 122 A = 65 and Z = 90


Program to check alphabets using ASCII value

/**
 * C program to check whether a character is alphabet or not
 */

#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("Character is an ALPHABET.\n");
    }
    else
    {
        printf("Character is NOT ALPHABET.\n");
    }

    return 0;
} 


Enhance your skills by learning this program using conditional operator.


Output
Enter any character: b
Character is an 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