Table of Contents
Introduction
In this C program, we will explore how to check if a character is an alphabet or not.
The Input screen asks the user to enter a character value to check whether it is an alphabet or a non-alphabet character.
To understand this program, you should know about
1. C programming operators
2. C nested if…else statement
We will learn this program using ASCII values.
Every character in C programming holds a particular ASCII value that ranges from 0 to 127.
For lowercase alphabets, the value ranges from 97 to 122; for uppercase alphabets, the value ranges from 65 to 90.
Thus, we will use this condition in the below program, and if the character entered by the user lies in the range of either lowercase or uppercase alphabets, then it will be considered a character.
Program
#include<stdio.h> #include<math.h> int main() { char c; printf("Enter a character:\n"); scanf("%c",&c); int Alpha=c; printf("ASCII value of %c is %d",c,Alpha); if( (Alpha>=65&& Alpha<=90) || (Alpha>=97&& Alpha<=122) ) //all alphabets whether lower case or upper case lies in between these ASCII value. { printf("\n%c is an alphabet",c); } else { printf("\n%c is not an alphabet",c); } return 0; }
Output
Explanation
The character value entered by the user is stored in variable ‘c’.
int Alpha=c;
The above statement looks like we have assigned character ‘c’ in the variable ‘Alpha’ of the int type, which is impossible since both belong to different data types.
The above statement is used to type caste the ‘char’ variable ‘c’ to the ‘int’ variable ‘Alpha’. Since we know a character holds an integer value thus, that value will be assigned to ‘Alpha’.
Thus, ‘Alpha’ holds the ASCII value of character ‘c’.
if( (Alpha>=65&& Alpha<=90) || (Alpha>=97&& Alpha<=122) )
There are two conditions written in the above if statement i.e., (Alpha>=65&& Alpha<=90) and (Alpha>=97&& Alpha<=122). If either of them is true, then the body of ‘if’ will be executed because they are operated with ‘||’ operator.
In the first output, the character is ‘+’, whose ASCII value does not lie in the given range.
In the second output, the character is ‘D’, whose ASCII value lies in the given range.
0 Comments