The Count Vowels and Consonants program in C is designed to count and display the number of vowels and consonants in a given string. This program typically involves iterating through each character of the string, checking whether it's a vowel or a consonant, and maintaining a count of each.
Implementation of Count Vowels and Consonants Program
Here’s a simple implementation of this program in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: For standard input and output functions.#include <ctype.h>
: For character handling functions liketolower()
andisalpha()
.
Variable Declarations:
char str[100]
: An array to hold the input string with a maximum length of 99 characters (the last character is reserved for the null terminator).int vowels = 0
: Counter for vowels, initialized to 0.int consonants = 0
: Counter for consonants, initialized to 0.int i = 0
: Loop counter for iterating through the string.
User Input:
- The program prompts the user to enter a string, which is read using
fgets()
. This function allows spaces in the input.
- The program prompts the user to enter a string, which is read using
Character Iteration:
- A
while
loop is used to iterate through each character of the string until the null terminator ('\0'
) is reached.
- A
Character Processing:
- Each character is converted to lowercase using
tolower()
for uniform comparison. - The
isalpha()
function checks if the character is a letter. - If the character is a vowel (checked against 'a', 'e', 'i', 'o', 'u'), the vowel counter is incremented.
- If it is not a vowel but is an alphabetic character, the consonant counter is incremented.
- Each character is converted to lowercase using
Display Results:
- After iterating through the string, the program prints the total counts of vowels and consonants.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter a string when prompted.
Example Input/Output
Input:
Output:
Conclusion
The Count Vowels and Consonants program in C is a practical exercise that demonstrates how to manipulate strings and utilize character handling functions. It reinforces the understanding of loops, conditionals, and basic string operations in C programming. This type of program can be easily extended or modified to include additional functionality, such as counting specific letters or ignoring certain characters.