C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Count vowels, consonants

C Program: Count vowels, consonants

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char str[200];

    int i, vowels = 0, consonants = 0;

 

    // Input string

    printf("Enter a string: ");

    gets(str); // unsafe, use fgets() in modern compilers

 

    // Traverse string

    for (i = 0; str[i] != '\0'; i++) {

        // Check for alphabets

        if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {

            // Check for vowels

            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')

                vowels++;

            else

                consonants++;

        }

    }

 

    // Display results

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

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

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a string: Hello World
Number of vowels: 3
Number of consonants: 7

OUTPUT 2 :
Enter a string: Programming in C
Number of vowels: 4
Number of consonants: 10

Explanation

  1. The program reads a string from the user.
  2. It iterates through each character:
    • If it’s an alphabet, it checks if it’s a vowel (a, e, i, o, u or uppercase equivalents).
    • If not, it’s a consonant.
  3. Non-alphabet characters (spaces, digits, punctuation) are ignored.

 

C Program: Count vowels, consonants

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char str[200];

    int i, vowels = 0, consonants = 0;

 

    // Input string safely

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);  // safer than gets()

 

    // Traverse string

    for (i = 0; str[i] != '\0'; i++) {

        // Check for alphabets

        if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {

            // Check for vowels

            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')

                vowels++;

            else

                consonants++;

        }

    }

 

    // Display results

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

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

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a string: Hello World
Number of vowels: 3
Number of consonants: 7

OUTPUT 2 :
Enter a string: Programming in C
Number of vowels: 4
Number of consonants: 10

Explanation

  1. The program reads a string from the user.
  2. It iterates through each character:
    • If it’s an alphabet, it checks if it’s a vowel (a, e, i, o, u or uppercase equivalents).
    • If not, it’s a consonant.
  3. Non-alphabet characters (spaces, digits, punctuation) are ignored.