C program to check if a given character is an alphabet, digit, or special character

Category: C Program
Tags: #cprogram#ifelse#conditional

Learn how to create a C program that distinguishes character types, exploring ASCII values and conditional checks. Enhance your C programming skills with this tutorial.

In this article, we'll explore how to create a simple C program that identifies the type of a given character.

Understanding Character Types

Characters in programming languages fall into different categories. Alphabets represent letters ('A' to 'Z' and 'a' to 'z'), digits represent numbers (0 to 9), and special characters encompass symbols, punctuation, and other non-alphanumeric characters.

C program to check if a given character is an alphabet, digit, or special character

Let's delve into the C programming language to create a program that determines whether a user-input character is an alphabet, digit, or a special character.

#include <stdio.h>

int main() {
    char ch;

    // Input from the user
    printf("Enter a character: ");
    scanf(" %c", &ch);

    // Checking character type
    if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
        printf("%c is an alphabet.", ch);
    } else if (ch >= '0' && ch <= '9') {
        printf("%c is a digit.", ch);
    } else {
        printf("%c is a special character.", ch);
    }

    return 0;
}

Output

Enter a character: #
# is a special character.

Here, the trick is to take input as character type so that we can store all types of input in single variable and then compare digits also as a character.

Character Type Check: The program checks if the entered character falls into the categories of alphabet, digit, or special character based on their ASCII values.

In this article, we've created a simple C program that efficiently determines whether a given character is an alphabet, digit, or a special character. Understanding ASCII values and utilizing conditional checks in C enables us to accurately classify characters based on their types.


Recommended Posts