C Exercises: Count the number of vowels in a given string using an inline function
C inline function: Exercise-7 with Solution
Write a C program to count the number of vowels in a given string using an inline function.
Sample Solution:
C Code:
#include <stdio.h>
#include <ctype.h>
inline int count_vowels(const char * str) {
int ctr = 0;
while ( * str != '\0') {
char ch = tolower( * str);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
ctr++;
}
str++;
}
return ctr;
}
int main() {
char str[] = "w3resource.com";
int vowels = count_vowels(str);
printf("The string \"%s\" contains %d vowels.\n", str, vowels);
char str1[] = "United States of America ";
vowels = count_vowels(str1);
printf("\nThe string \"%s\" contains %d vowels.\n", str1, vowels);
return 0;
}
Sample Output:
The string "w3resource.com" contains 5 vowels. The string "United States of America " contains 10 vowels.
Explanation:
The above count_vowels() function uses a while loop to iterate over each character in the string. It converts each character to lowercase using the tolower() function and then checks if it is a vowel (i.e., 'a', 'e', 'i', 'o', or 'u'). If the character is a vowel, it increments a counter variable. Finally, the function returns the total count of vowels in the string.
In the main() function, we declare a test string, call the count_vowels() function on it, and print the result.
Flowchart:
C Programming Code Editor:
Previous: Convert a temperature from Celsius to Fahrenheit and vice versa.
Next: Check if a given integer is prime using an inline function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/inline_function/c-inline-function-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics