Complementary task for topic: 5

M Nemeth · 2023-08-29 15:21:04.620218'

Simple strings: Vowel Counter

Simple strings: Vowel Counter

Write a C program that uses scanf() to read a string from the user and then counts the number of vowels (a, e, i, o, u) in the entered string. Display the count of vowels using printf().

Hint: Traverse the string, count if the actual character is a vowel. You can use a simple function to decide if it is vowel or not.

Solution
#include 

int is_vowel(char c) {
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
            c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
}

int main() {
    char str[100];
    int count = 0;

    printf("Enter a string: ");
    scanf("%99[^\n]", str); // Read the string with spaces

    // Count the number of vowels
    for (int i = 0; str[i] != '\0'; i++) {
        if (is_vowel(str[i])) {
            count++;
        }
    }

    printf("Number of vowels: %d\n", count);

    return 0;
}



Explanation
The program uses a is_vowel() function to check if a character is a vowel. It returns 1 if the character is a vowel and 0 otherwise.

The user is prompted to enter a string using printf().

The string is read using scanf() with the %[^\n] format specifier, allowing the input to include spaces.

The program uses a for loop to iterate through each character of the input string.

Inside the loop, the is_vowel() function is used to check if the character is a vowel.

If the character is a vowel, the count variable is incremented
< < previous    next > >