Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print number of words, vowels and frequency of each character
In C programming, string analysis is a common task where we need to count words, vowels, and find the frequency of specific characters. This program demonstrates how to analyze a string by counting these different elements in a single pass.
Syntax
// String traversal for character analysis
for(i = 0; str[i] != '\0'; i++) {
// Character comparison and counting logic
}
Algorithm
START Step 1: Declare string array, character variable, and counters (freq=0, vowels=0, words=0) Step 2: Input string and target character Step 3: Loop through each character in string until '\0' Step 3.1: If current character matches target character, increment freq Step 3.2: If current character is vowel (a,e,i,o,u), increment vowels Step 3.3: If current character is space, increment words Step 4: Display frequency, vowel count, and word count STOP
Example
Here's a complete program that counts words, vowels, and character frequency −
Note: This program uses
fgets()instead ofgets()for safer string input, asgets()is deprecated in modern C.
#include <stdio.h>
#include <string.h>
int main() {
char str[1000], ch;
int i, freq = 0, vowels = 0, words = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove newline character if present
if (str[strlen(str) - 1] == '<br>') {
str[strlen(str) - 1] = '\0';
}
printf("Enter a character to find frequency: ");
scanf(" %c", &ch);
for (i = 0; str[i] != '\0'; i++) {
// Count frequency of specific character
if (ch == str[i]) {
freq++;
}
// Count vowels (both lowercase and uppercase)
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++;
}
// Count words by counting spaces
if (str[i] == ' ') {
words++;
}
}
// Add 1 to words count (last word after final space)
if (strlen(str) > 0) {
words++;
}
printf("\nFrequency of '%c': %d<br>", ch, freq);
printf("Total vowels: %d<br>", vowels);
printf("Total words: %d<br>", words);
return 0;
}
Output
Enter a string: I love PrograMMIng Enter a character to find frequency: M Frequency of 'M': 2 Total vowels: 6 Total words: 3
Key Points
- Words are counted by counting spaces and adding 1 for the last word
- Vowel checking includes both uppercase and lowercase letters
- Character frequency is case-sensitive
- The program handles strings with multiple spaces correctly
Conclusion
This program efficiently analyzes strings by traversing them once and performing multiple counting operations. It demonstrates fundamental string processing concepts including character comparison, conditional counting, and safe string input handling.
Advertisements
