Problem: Write a C program to count the number of vowels and consonants in the given string.

#include <stdio.h>

int main() {
    char string[100];
    int i, vowels = 0, consonants = 0;

    // Input string from user
    printf("Enter a string: ");
    fgets(string, sizeof(string), stdin);

    // Iterate through each character of the string
    for (i = 0; i < strlen(string); i++) {
        // Check if the current character is a vowel
        if (string[i] == 'a' || string[i] == 'e' || string[i] == 'i' || string[i] == 'o' || string[i] == 'u' ||
            string[i] == 'A' || string[i] == 'E' || string[i] == 'I' || string[i] == 'O' || string[i] == 'U') {
            vowels++;
        }
        // Check if the current character is a consonant
        else if ((string[i] >= 'a' && string[i] <= 'z') || (string[i] >= 'A' && string[i] <= 'Z')) {
            consonants++;
        }
    }

    // Print the number of vowels and consonants
    printf("Vowels: %d \n", vowels);
    printf("Consonants: %d", consonants);

    return 0;
}

Output:

Enter a string: pencil programmer
Vowels: 5
Consonants: 11

In the above program, we ask user to enter a string and then count the number of vowels and consonants using a for loop.

Using for loop, we iterate through each character of the string. For this we use the strlen() function to know the number of characters in the string. This helps us to determine the number of iterations.

Within the loop, we then use an if-else statement to check if the current character is a vowel or a consonant.

If the character is a vowel, we increment the vowels count, otherwise, we increment the count of consonants.

At last, we print the count of vowels and consonants as output.

Leave a Reply