Summary: This C program counts the number of vowels and consonants in a given string. It processes the input character by character, checks if each character is a letter, and determines if it is a vowel or a consonant.
#include <stdio.h>
#include <string.h>
// Function to check if a character is a vowel
int isVowel(char ch) {
// Convert to lowercase manually
if (ch >= 'A' && ch <= 'Z') {
ch = ch + 32; // Convert uppercase to lowercase
}
// Check for vowels
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
// Function to check if a character is an alphabet (manual check)
int isAlphabet(char ch) {
return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'));
}
void countVowelsAndConsonants(char s[]) {
int vowels = 0, consonants = 0;
// Loop through each character of the string
for (int i = 0; s[i] != '\0'; i++) {
// Check if the character is an alphabet
if (isAlphabet(s[i])) {
// Check for vowels
if (isVowel(s[i])) {
vowels++;
}
// Otherwise, it's a consonant
else {
consonants++;
}
}
}
// Print the results
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
}
int main() {
char s[1001]; // String length limit 1000 + 1 for null terminator
// Get the input string using scanf
printf("Enter the string: ");
scanf("%[^\n]%*c", s); // Reads the entire line including spaces
// Count vowels and consonants
countVowelsAndConsonants(s);
return 0;
}
Program Overview:
This program counts the number of vowels and consonants in a given string. It processes each character in the string to determine whether it is a vowel or a consonant.
isVowel():This function checks whether a character is a vowel.
'a', 'e', 'i', 'o', or 'u'.isAlphabet():This function checks whether a character is an alphabet.
'A' to 'Z' or 'a' to 'z'.countVowelsAndConsonants():This function counts the number of vowels and consonants.
isAlphabet().isVowel() to determine if the character is a vowel.scanf("%[^\n]%*c", s) reads the entire line until a newline character.countVowelsAndConsonants() is called to count and print the results.O(n) where n is the length of the string since each character is processed once.O(1) as the operations are performed in-place with minimal extra space.