Tenkin
Tenkin

Reputation: 25

Else if statement in C so that all non-alphabet characters come with a seperate message

I'm just starting to learn C and one of the questions I'm doing asks to create a program with else if statements to determine whether a letter is a vowel or a consonant. This is what I've got so far.

#include <stdio.h>

int main()
{
    char ch;
    printf ("Type your character: ");
    scanf ("%c", &ch);
    if (ch == 'A' || ch == 'a' || ch == 'E' || ch == 'e' || ch == 'I' || 
        ch == 'i' || ch == 'O' || ch == 'o' || ch == 'U' || ch == 'u')
        printf ("%c is a vowel.", ch);
    else if (ch < 'A' && ch > 'Z' && ch < 'a' && ch > 'z')
        printf ("%c is not part of the alphabet.", ch);
    else
        printf ("%c is not a consonant.", ch);
    return 0;
}

This does work in showing if a letter is a vowel but when I input any character that isn't a letter in the alphabet, it shows "ch is not a consonant" instead of "ch not part of the alphabet".

else if (ch < 'A' && ch > 'Z' && ch < 'a' && ch > 'z')
    printf ("%c is not part of the alphabet.", ch);
else
    printf ("%c is not a consonant.", ch);

My logic behind this is that I want all characters lower than 'A', higher than 'Z', lower than 'a' and higher than 'z' in the ASCII table to come up as not part of the alphabet and all the remaining characters, A to Z and a to z to come up as consonants if it isn't a vowel.

Also, I understand there is probably much quicker ways to do this like the !isalpha function, but I'm just curious as to why this way doesn't work.

Any help would be appreciated

Upvotes: 0

Views: 638

Answers (1)

Muslimbek Abduganiev
Muslimbek Abduganiev

Reputation: 941

Your conditioning is wrong. You should use some or s:

if (ch < 'A' || (ch > 'Z' && ch < 'a') || ch > 'z')...

You might want to learn about boolean operations a little bit more.

Upvotes: 2

Related Questions