Skip to content

← Back to Overview

Check if Character is Alphabet

Concept Explanation

What is it?

This program determines whether a given character is an alphabet (a letter from A-Z or a-z). It distinguishes letters from numbers, symbols, and whitespace.

Why is it important?

Character classification is a common task in programming. It's used for input validation, text processing, parsing, and lexical analysis (breaking down text into meaningful units). Understanding how to identify alphabets is a foundational step in handling more complex text data.

Where is it used?

  • Input Validation: Ensuring that user input, such as names or specific codes, contains only alphabetic characters.
  • Text Processing: Analyzing text for word counts, filtering non-alphabetic characters, or converting case.
  • Lexical Analysis: In compilers or interpreters, identifying identifiers and keywords.
  • Form Design: Guiding users to enter appropriate data in fields (e.g., name fields should only accept alphabets).

Real-world example

When you sign up for an online service and enter your name, the system often checks if the characters you entered are valid letters. If you accidentally type a number or a symbol, it might prompt you to correct it, using logic similar to this program.


Algorithm

  1. Start.
  2. Get a single character (ch) from the user.
  3. Check if ch falls within the ASCII/Unicode range for uppercase letters (A-Z) OR lowercase letters (a-z).
  4. If it matches either range, ch is an alphabet.
  5. Else, ch is not an alphabet.
  6. Display the result.
  7. End.

Edge Cases: - Inputting more than one character (handled by taking only the first character or explicit error). - Numbers or symbols: These should be correctly identified as non-alphabetic. - Whitespace: Should also be non-alphabetic.


Implementations

import java.util.Scanner;

public class IsAlphabet {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a character: ");
        char ch = scanner.next().charAt(0);

        System.out.println("Input Character: " + ch);

        if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
            System.out.println("The character '" + ch + "' is an ALPHABET.");
        } else {
            System.out.println("The character '" + ch + "' is NOT an alphabet.");
        }

        scanner.close();
    }
}
# Get a character from user
char_input = input("Enter a character: ")

# Ensure only one character is processed
if len(char_input) == 1:
    character = char_input[0]

    if character.isalpha():
        print(f"The character '{character}' is an ALPHABET.")
    else:
        print(f"The character '{character}' is NOT an alphabet.")
else:
    print("Please enter a single character.")
#include <stdio.h>
#include <ctype.h> // For isalpha()

int main() {
    char ch;

    printf("Enter a character: ");
    scanf(" %c", &ch); // space before %c to consume any leftover newline character

    printf("Input Character: '%c'", ch);

    if (isalpha(ch)) {
        printf("The character '%c' is an ALPHABET.", ch);
    } else {
        printf("The character '%c' is NOT an alphabet.", ch);
    }

    return 0;
}
SET SERVEROUTPUT ON;
DECLARE
  input_char  CHAR(1) := '&Enter_a_Character';
  is_alpha    BOOLEAN;
BEGIN
  DBMS_OUTPUT.PUT_LINE('Input Character: ' || input_char);

  -- Check if the character is within the ASCII range for uppercase or lowercase letters
  IF (input_char >= 'A' AND input_char <= 'Z') OR (input_char >= 'a' AND input_char <= 'z') THEN
    is_alpha := TRUE;
  ELSE
    is_alpha := FALSE;
  END IF;

  IF is_alpha THEN
    DBMS_OUTPUT.PUT_LINE('The character "' || input_char || '" is an ALPHABET.');
  ELSE
    DBMS_OUTPUT.PUT_LINE('The character "' || input_char || '" is NOT an ALPHABET.');
  END IF;
END;
/

Explanation

  • Java: Uses direct ASCII/Unicode comparison (ch >= 'a' && ch <= 'z') or the Character.isLetter() method. Scanner is used for character input.
  • Python: Leverages the built-in str.isalpha() method, which is very convenient for character classification. Handles single-character input.
  • C: Employs the isalpha() function from the <ctype.h> library, which checks if a character is an alphabetic letter. scanf(" %c", ...) reads a single character, skipping whitespace.
  • Oracle: Implemented in PL/SQL. Uses direct character range comparisons (>= and <=) within an IF-ELSE block. Substitution variables (&Enter_a_Character) prompt for input.

Complexity Analysis

  • Time Complexity: O(1) - The character comparison operations are constant time.
  • Space Complexity: O(1) - A fixed number of variables are used.

Flowchart

graph TD
    A[Start] --> B[Get Character ch]
    B --> C{ch is A-Z OR a-z?}
    C -- Yes --> D[Display ALPHABET]
    C -- No --> E[Display NOT ALPHABET]
    D --> F[End]
    E --> F

Sample Dry Run

Step ch Condition (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') Description
Input 'k' ('k' >= 'a' && 'k' <= 'z') = True User enters 'k'
Decision 'k' True Character is an alphabet
Output - - Display "'k' is an ALPHABET."
End - - Program terminates
Input '7' ('7' >= 'a' && '7' <= 'z') = False
('7' >= 'A' && '7' <= 'Z') = False
User enters '7'
Decision '7' False Character is not an alphabet
Output - - Display "'7' is NOT an alphabet."
End - - Program terminates

Practice Problems

Easy

  • Modify the program to check if a character is a digit.
  • Check if a character is uppercase or lowercase.

Medium

  • Write a program that counts the number of alphabets, digits, and special characters in a given string.
  • Validate if a given string contains only alphabetic characters.

Hard

  • Implement a simple lexical analyzer that can identify different token types (alphabets, numbers, operators) in a basic expression.

"The road to success is always under construction." - Lily Tomlin