Home > other >  Only detects the first element of the array when it's compared with the input. I've tried
Only detects the first element of the array when it's compared with the input. I've tried

Time:05-23

It was supposed to be a function that detects when it's a vowel. But, it didn't work out as expected

#include <stdio.h>
#include <conio.h>

// It didn't work out. It failed

// It was supposed to be a function that detects when it's a vowel.
// But, it didn't work out as expected

int isVowel(char c) {
    char letters[] = {'A', 'I', 'U', 'E', 'O', 'a', 'i', 'u', 'e', 'o'};
    for (int i = 0; i <= 9; i  ) /* It detects A, but nothing else*/ {
        if (letters[i] == c)
            return printf("A vowel\n");
        else 
            return printf("Not a vowel \n");
    }

}

int main() {
    char c;
    printf("Press a key: ");
    do {
        c = getch();
        char ans = isVowel(c);
    } while(c != 13);
}

Any way I can fix it up to compare the whole array?

CodePudding user response:

You are returning after you check for 'A' regardless of whether it matches. You want to check all the possible vowels until you match or hit the end of the list. I also would make the function void since you ignore the return code.

void isVowel(char c) {
    char letters[] = {'A', 'I', 'U', 'E', 'O', 'a', 'i', 'u', 'e', 'o'};
    for (int i = 0; i <= 9; i  ) /* It detects A, but nothing else*/ {
        if (letters[i] == c)
            printf("A vowel\n");
            return;
    }

    printf("Not a vowel \n");
 }

}

  • Related