Skip to main content

Check string consists of alphabet only

Short answer

isAllAlpha() loops through string; if any character is not a letter (via isalpha()), returns0. If all are letters and not empty, returns1. main() reads string and prints appropriate message.

Write a program to read a string and check whether it consists of Alphabet or not. Use user defined function to accomplish the task.

Logic. The function isAllAlpha() visits each character of the string. If any character is not a letter (isalpha() from <ctype.h> fails, e.g. a digit, space or symbol), it returns 0 at once. If the loop finishes, all characters are letters and it returns 1. An empty string is treated as not valid.

#include <stdio.h>
#include <ctype.h>

/* returns 1 if every character is a letter, else 0 */
int isAllAlpha(char s[])
{
    if (s[0] == '\0')
        return 0;
    for (int i = 0; s[i] != '\0'; i++)
        if (!isalpha((unsigned char)s[i]))
            return 0;
    return 1;
}

int main(void)
{
    char str[100];
    printf("Enter a string: ");
    scanf("%99s", str);
    if (isAllAlpha(str))
        printf("\"%s\" consists of alphabets only\n", str);
    else
        printf("\"%s\" does not consist of alphabets only\n", str);
    return 0;
}

Sample run (the digit 2 makes the check fail)

Input: Pulchowk2

Enter a string: "Pulchowk2" does not consist of alphabets only

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →