Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    C Program to Count Vowels in a String

    C Programming Examples


    Counting vowels is a common task in text processing. This tutorial guides you through writing a C program that counts vowels in a string.

    What Are Vowels?

    Vowels are the speech sounds represented by the letters "A," "E," "I," "O," and "U". In the English alphabet, these five letters are crucial for word construction and pronunciation. Recognizing vowels in strings is necessary for many text-processing tasks.

    Basic Vowel Count Program in C

    Here is the simple C program that counts the number of vowels in a given string:

    #include <stdio.h>
    
    int main() {
        char str[100];  // String array declaration with a fixed size
        int count = 0;  // Variable to keep track of vowel count
    
        printf("Enter a string: ");
        fgets(str, sizeof(str), stdin); // fgets is used to read a string from the user
    
        for(int i = 0; str[i] != '\0'; i++) { // Iterate over each character
            // Using a if statement to check for vowels, both lowercase and uppercase
            if(str[i]=='a' || str[i]=='e' || str[i]=='i' || 
               str[i]=='o' || str[i]=='u' || str[i]=='A' || 
               str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U') {
                count++; // Increment count for each vowel
            }
        }
    
        printf("Number of vowels in the string: %d\n", count); // Output the result
    
        return 0;
    }
    

    Program Output:

    Enter a string: Hello W3schools
    Number of vowels in the string: 4

    Here in the above example, the vowels are "e" and "o" in "Hello" and "o" and "o" in "w3schools".

    Explanation:

    1. The program begins by declaring a char array named str to hold the user's input and an integer count for the number of vowels.
    2. It prompts the user to enter a string and reads the input using fgets to prevent buffer overflow.
    3. A for loop iterates through each character in the string until it hits the null terminator ('\0'), which signifies the end of the string.
    4. An if statement checks for vowels. If one is found, the count is incremented.
    5. After the loop finishes, the program prints out the number of vowels found.

    Improved Vowel Count Program in C

    While the basic program works well, it can be refined to improve its functionality and make it more efficient:

    #include <stdio.h>
    #include <ctype.h>  // Include ctype.h for character type functions
    #include <string.h> // Include string.h for string functions
    
    #define MAX_STR_LEN 100 // Define a constant for the maximum string length
    
    // Function to count vowels in a given string
    int countVowels(const char *str) {
        int count = 0; // Vowel counter
        size_t length = strlen(str); // Calculate the string length once to optimize the loop
    
        for (size_t i = 0; i < length; i++) { // Use size_t for index, which is the proper type for sizes
            char lower = tolower((unsigned char)str[i]); // Cast to unsigned char to avoid undefined behavior
            // Check for vowels with a switch statement
            switch (lower) {
                case 'a': case 'e': case 'i': case 'o': case 'u':
                    count++;
                    break;
            }
        }
    
        return count; // Return the total count of vowels
    }
    
    int main() {
        char str[MAX_STR_LEN]; // Allocate buffer for string input
    
        printf("Enter a string: "); // Ask for user input
        // Check for input errors and null termination
        if (!fgets(str, MAX_STR_LEN, stdin)) {
            printf("Error reading string.\n"); // Error message
            return 1;
        }
    
        str[strcspn(str, "\n")] = 0; // Remove trailing newline character, if any
    
        // Call countVowels and display the result
        printf("Number of vowels: %d\n", countVowels(str));
    
        return 0;
    }

    Enhancements Made:

    1. Function Usage: Separated the logic into a countVowels function for better code organization and reusability.
    2. Performance Optimization: The strlen function is called once before the loop instead of in each iteration.
    3. Type Safety: The tolower function is used with an (unsigned char) cast to avoid undefined behavior with negative char values.
    4. String Handling: Added code to remove the newline character from the input string.
    5. Error Handling: Included a check to ensure fgets successfully reads

    Conclusion

    You just learned how to count the vowels in a string in a C program. This program can handle any text length and is a fundamental skill for text analysis in C. Try modifying the code to add new features or to count vowels in a particular way.



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.