C Program to Count the Number of Vowels, Consonants and so on

C Examples Sort Elements in Lexicographical Order (Dictionary Order) Copy String Without Using strcpy() Concatenate Two Strings Find the Length of a S

To understand this example, you should have the knowledge of the following C programming topics:

 

·       C Arrays

·       C Multidimensional Arrays

·       Pass arrays to a function in C

·       C for Loop

·       C Arrays

·       C Pointers

·       Relationship Between Arrays and Pointers

·       C Pointers

·       C Pass Addresses and Pointers

·       C Dynamic Memory Allocation

·       C Programming Strings

 

Program to count vowels, consonants, etc.

#include <stdio.h>
int main() {

  char line[150];
  int vowels, consonant, digit, space;

  // initialize all variables to 0
  vowels = consonant = digit = space = 0;

  // get full line of string input
  printf("Enter a line of string: ");
  fgets(line, sizeof(line), stdin);

  // loop through each character of the string
  for (int i = 0; line[i] != '\0'; ++i) {

    // convert character to lowercase
    line[i] = tolower(line[i]);

    // check if the character is a vowel
    if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
        line[i] == 'o' || line[i] == 'u') {

      // increment value of vowels by 1
      ++vowels;
    }

    // if it is not a vowel and if it is an alphabet, it is a consonant
    else if ((line[i] >= 'a' && line[i] <= 'z')) {
      ++consonant;
    }

    // check if the character is a digit
    else if (line[i] >= '0' && line[i] <= '9') {
      ++digit;
    }

    // check if the character is an empty space
    else if (line[i] == ' ') {
      ++space;
    }
  }

  printf("Vowels: %d", vowels);
  printf("\nConsonants: %d", consonant);
  printf("\nDigits: %d", digit);
  printf("\nWhite spaces: %d", space);

  return 0;
}


Output

 
Enter a line of string: C++ 20 is the latest version of C++ yet.
Vowels: 9
Consonants: 16
Digits: 2
White spaces: 8

Here, the string entered by the user is stored in the line variable.

Initially, the variables vowelconsonantdigit, and space are initialized to 0.

Then, a for loop is used to iterate over the characters of the string. In each iteration, we:

convert the character to lowercase using the tolower() function

check whether the character is a vowel, a consonant, a digit, or an empty space. Suppose the character is a consonant. Then, the consonant variable is increased by 1.

When the loop ends, the number of vowels, consonants, digits, and white spaces are stored in variables vowelconsonantdigit, and space respectively.

Note: We have used the tolower() function to simplify our program. To use this function, we need to import the ctype.h header file.

 


Labels : #c ,#code ,#examples ,

Post a Comment