Introduction
A string is a data type similar to an integer and a floating-point unit that is used to represent text rather than numbers in programming. It is made up of a series of characters that may include spaces and integers. The words "hamburger" and "I ate 3 hamburgers," for example, are both strings.
There are 26 letters in English in the alphabet, five of which are vowels (a, e, i, o, u), while the rest are consonants.
The vowels a, e, i, o, and u can be lowercase or uppercase, and the computer will find and count both.
Also Read, Binary to Hex Converter and C Static Function.
Problem Statement
Count the number of vowels in a string using C.
Let us see an example:
By default, the compiler appends a null character \0 to the end of a sequence of characters wrapped in double quotation marks.
Output:
You can also read about dynamic array in c and Tribonacci Series.
Idea
The idea behind this problem is simple, we take a count variable and traverse the string. If we find any vowel(a, e, i, o, u) then we increase the count variable by one. And in the end, we print that count variable. Hence we can find the total number of variables in a string.
Algorithm
- set the count to 0
- Loop through the string until it reaches a null character.
- Compare each character to the vowels a, e, I o, and u.
- If both are equal, increase the count by one.
- Print the count at the end.
Implementation
/* Count the number of vowels in a string using C */
#include <stdio.h>
#include <math.h>
#include <string.h>
void Solve()
{
unsigned short count = 0, vowels = 0;
char str[100], c;
printf("Enter a string in which you want to find number of vowels: ");
scanf("%[^\n]", str);
while(str[count] != '\0')
{
c = str[count];
if(c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I'
|| c == 'o' || c == 'O' || c == 'u' || c == 'U') {
vowels++;
printf("%c", c);
}
count++;
}
printf("\n");
printf("NUMBER OF VOWELS In Given string Are: %hu \n", vowels);
}
int main()
{
Solve();
return 0;
}
Time Complexity: O(N) where n is the length of the string.
Auxiliary Space: Constant space.
Output
Program Explanation
Here is the process. The if condition checks for both lowercase and uppercase vowels inside the while loop. The vowels variable is incremented if the requirement is met.
The printf() statement also prints the vowel included within the condition.
You can practice by yourself with the help of the C online compiler.