Write a program in C/C++ to count the number of vowels and consonants in a string using pointers.
Example,
Input MyNameIsJohnSmith Output Consonants: 12 Vowels: 5
Steps
- Let str[] be the input string.
- Initialize c1 = 0 and c2 = 0. c1 stores the number of consonants and c2 stores the number of vowels.
- Read each character of str[] using a pointer and perform the following operations on each character.
- If the current character is a consonant, increment c1.
- If the current character is a vowel, increment c2.
- Number of consonants = c1
- Number of vowels = c2
#include<stdio.h>
#include<string.h>
int main() {
char str[300], * ptr, c1, c2;
// c1: number of consonants
// c2: number of vowels
c1 = c2 = 0;
printf("Enter String: ");
gets(str);
// storing the address of first character in str[] in ptr
ptr = str;
while (*ptr != '\0') {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u' || *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U')
++c2;
else if ((*ptr >= 'a' && *ptr <= 'z') || (*ptr >= 'A' && *ptr <= 'Z'))
++c1;
// move to next address ( ~ next character )
++ptr;
}
printf("Number of Consonants: %d\n", c1);
printf("Number of Vowels: %d", c2);
}
Output
Enter String: HelloWorld
Number of Consonants: 7
Number of Vowels: 3
Read
- Count the number of unique characters in a string in C/C++
- Insert a new node to a sorted linked list such that the resultant linked list is also sorted