C Program to Count Vowels and Consonants in a String using Pointer

June 5, 2021

In this tutorial, we will write a C program to count vowels and consonants in a given String using Pointer.

To understand this program you should know the basics of Arrays and pointers in C.

Program to count Vowels and Consonants in String using Pointer

In the following program we have declared a char array str to hold the input string which we store in the array using fgets() function. We have assigned the base address of array (address of first element) to the pointer p. We cycled through all the characters of the input string by using pointer p inside while loop and incrementing the pointer value on every iteration.

#include <stdio.h>
int main()
{
    char str[100];
    char *p;
    int  vCount=0,cCount=0;

    printf("Enter any string: ");
    fgets(str, 100, stdin);

    //assign base address of char array to pointer
    p=str;

    //'\0' signifies end of the string
    while(*p!='\0')
    {
        if(*p=='A' ||*p=='E' ||*p=='I' ||*p=='O' ||*p=='U'
        		||*p=='a' ||*p=='e' ||*p=='i' ||*p=='o' ||*p=='u')
            vCount++;
        else
            cCount++;
        //increase the pointer, to point next character
        p++;
    }

    printf("Number of Vowels in String: %d\n",vCount);
    printf("Number of Consonants in String: %d",cCount);
    return 0;
}

admin