Program to Count the Number of Vowels - (C Programs)
In this tutorial, we'll discuss how to write a C program to count the number of vowels in a given string.
Syntax
The syntax for counting the number of vowels in C is as follows:
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100];
int vowels = 0;
int i;
printf("Enter a sentence: ");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++)
{
if (tolower(str[i]) == 'a' || tolower(str[i]) == 'e' || tolower(str[i]) == 'i' || tolower(str[i]) == 'o' || tolower(str[i]) == 'u')
{
vowels++;
}
}
printf("Number of vowels in the sentence: %d\n", vowels);
return 0;
}
Example
Suppose you have the string "The quick brown fox jumps over the lazy dog." To count the number of vowels in this string, you would use the following C program:
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100] = "The quick brown fox jumps over the lazy dog.";
int vowels = 0;
int i;
for (i = 0; str[i] != '\0'; i++)
{
if (tolower(str[i]) == 'a' || tolower(str[i]) == 'e' || tolower(str[i]) == 'i' || tolower(str[i]) == 'o' || tolower(str[i]) == 'u')
{
vowels++;
}
}
printf("Number of vowels in the sentence: %d\n", vowels);
return 0;
}
Output
The output of the above program will be:
Number of vowels in the sentence: 11
Explanation
This C program uses a for loop to iterate through each character in the string. It uses the tolower
function to convert each character to lowercase before checking if it is a vowel. If the character is a vowel, the program increments the vowels
counter. Finally, the program outputs the total number of vowels found in the string.
Use
This C program can be used to count the number of vowels in any given string.
Summary
In this tutorial, we discussed how to write a C program to count the number of vowels in a given string. We covered the syntax, example, output, explanation, use, and summary of the program. By understanding this program, you can easily modify it to count the number of other characters in a string as well.