How to detect a alphabet if its a vowel or not with C? Here is my programme
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
int main(){
char input;
scanf("%c", &input);
if(isupper(input)){
printf("it's capital letter.\n");}
else{
printf("it's small letter.\n");}
int C = ((int)input); //Change C from a char to sacii code
int intarray[10] = {65, 69, 73, 79, 85, 97, 101, 105, 111, 117}; //array of vowel
for(int i = 0; i < 10; i++){
if(C == intarray[i]){ //cheaking if C is a vowel or not
printf("Yes\n"); //print if it is
break;}
else{
printf("No\n"); //print if not
break;}
}
INPUT
o
OUTPUT
it’s a small letter.
No
>Solution :
You have a simple logic flow in your program.
The rules are:
- It is a vowel if you found one element in your array that matches.
- It is not a vowel if you do not find any matching value in your array.
That implies that you must search the whole array to find a vowel. Only after reaching the end of your array you can be sure it is not a vowel.
Besides that you should not use magic numbers if you want to store characters.
Try this:
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
int main(void)
{
char input;
scanf("%c", &input);
if (isupper(input)) {
printf("it's capital letter.\n");
}
else {
printf("it's small letter.\n");}
static const char vowels[] = "aeiouAEIOU";
bool found = false;
for (int i = 0; i < 10; i++) {
if (C == vowels[i]) { //cheaking if C is a vowel or not
found = true;
break; // Do not continue search.
}
}
if (found == true) {
printf("Yes\n"); //print if it is a vowel
}
else {
printf("No\n"); // No vowel found.
}
}
}
I changed that vowel array to a string, i.e. I added space for nul-terminator.
That means you could use standard functions like strchr to check if a character is in that string.
That for loop would not be required then:
if (strchr(vowels, c) != NULL)
found = true; // We have a vowel