C program to check whether a character is alphabet or not

Previous Program Next Program

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. Logic to check if a character is alphabet or not in C program.

Example

Input

Input character: a

Output

'a' is alphabet

Required knowledge

Basic C programming, Use of relational operator, If else

Logic to check alphabets

Characters in C programming internally are represented as an integer known as ASCII value. Hence we can easily perform relational operations such as - > < >= <= == != on characters. In C every printable symbols that appears on keyboard is treated as a characters and has an ASCII value.

To check if a character is alphabet or not. We only got to check if given character in between a-z, A-Z or not. Note: a and A both are different and have different ASCII values.

Let us write a step by step descriptive logic to check alphabets

  1. Read a character and store in some variable say ch.
  2. Check if ch >= 'a' AND ch <= 'z' or ch >= 'A' AND ch <= 'Z'. Then it is an alphabet.

Let us implement the logic on to a C program

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

    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 other approaches to solve the given program.

Output
Enter any character: b
Character is an ALPHABET.

Happy coding ;)

You may also like

Previous Program Next Program
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
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment