This is is a C++ Program to Count the Number of Vowels/Consonants/Numbers/Special Characters in a String.
The program takes a string and counts the number of vowels, consonants, numbers and special characters in the string and prints them.
1. The program takes a string.
2. Using if else condition, the string is checked for vowels, consonants, numbers and special characters and counted.
3. The result is printed.
4. Exit.
Here is the source code of C++ Program to Count the Number of Vowels/Consonants/Numbers/Special Characters in a String. The program output is shown below.
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char str[50];
int v = 0, c = 0, n = 0, s = 0;
cout << "Enter a string : ";
gets(str);
for (int i = 0; str[i]!='\0'; ++i)
{
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')
++v;
else if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
++c;
else if (str[i] >= '0' && str[i] <= '9')
++n;
else
++s;
}
cout << "Number of vowels : " << v;
cout << "\nNumber of consonants : " << c;
cout << "\nNumber of numbers :" << n;
cout << "\nNumber of special characters : " << s;
return 0;
}
1. The user is asked to enter a string. Using a string function it is stored in ‘str’.
2. Variables ‘v’, ‘c’, ‘n’, ‘s’ are initialized to count vowels, consonants, numbers and special characters respectively.
3. Using nested if else condition, if any of the characters are encountered, their respective variables are incremented.
4. The result is then printed.
Case 1 : Enter a string : Welcome to the world! Number of vowels : 6 Number of consonants : 11 Number of numbers :0 Number of special characters : 4 Case 2 : Enter a string : [email protected]@ ([email protected]& 24 Number of vowels : 1 Number of consonants : 3 Number of numbers :2 Number of special characters : 8 Case 3 : Enter a string : 63M5/888s Number of vowels : 0 Number of consonants : 2 Number of numbers :6 Number of special characters : 1
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy C++ Books
- Apply for Computer Science Internship
- Buy Programming Books
- Practice Computer Science MCQs
- Apply for Information Technology Internship