🔡 Count Vowels and Consonants in C
This tutorial will help you write a C program to count the number of vowels and consonants in a given string. We'll implement it in two ways:
- ✅ Using a custom function
- 🛠️ Without using any function
✅ Method 1: With Function
#include <stdio.h>
#include <ctype.h>
void countVowelsAndConsonants(char str[], int *vowels, int *consonants) {
*vowels = *consonants = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
(*vowels)++;
} else {
(*consonants)++;
}
}
}
}
int main() {
char str[100];
int vowels, consonants;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
countVowelsAndConsonants(str, &vowels, &consonants);
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
🧠 Explanation:
- The function uses
tolower()
to simplify comparison. - Checks each character: if alphabetic, it’s either a vowel or consonant.
🛠️ Method 2: Without Function (All logic in main()
)
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
📌 Output Example:
Enter a string: Hello World Vowels: 3 Consonants: 7
📌 Summary
This program teaches you how to use ctype.h
functions like tolower()
and how to count characters with conditions. It’s a great beginner exercise for string analysis in C.
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন