C/C++ Program to count the number of vowels and consonants in a string using pointers

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

  1. Let str[] be the input string.
  2. Initialize c1 = 0 and c2 = 0. c1 stores the number of consonants and c2 stores the number of vowels.
  3. 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.
  4. Number of consonants = c1
  5. 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

Leave a Comment

Your email address will not be published. Required fields are marked *