Write a program in C to count the number of vowels and consonants in a string. You can use fgets to read the characters.
Question
Write a program in C to count the number of vowels and consonants in a string. You can use fgets to read the characters.
Solution
Sure, here is a simple C program that counts the number of vowels and consonants in a string:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, vowels = 0, consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for(i = 0; str[i]!='\0'; ++i) {
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 if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z')) {
++consonants;
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
This program works by reading a string from the user using fgets(). It then iterates over each character in the string. If the character is a vowel (either lowercase or uppercase), it increments the vowels counter. If the character is a consonant (i.e., it is a letter but not a vowel), it increments the consonants counter. Finally, it prints out the number of vowels and consonants.
Similar Questions
letter countWrite a C program that will analyze a line of text and will print the number of words, the number of consonants, and the number of vowels in the text.Testcase:Input:Programming is fun!Output:3 // Number of words:11 // Number of consonants:5 // Number of vowels:
Read any string and display the vowels
find the number of alphabet vowels and words in input using string
#Write a Python function count_vowels(text) that takes a string as input and returns the count of vowels (a, e, i, o, u) in the input string, ignoring case.
Write a C program to check whether an alphabet is vowel or consonant using switch case
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.