w3resource logo


C Programming Exercises

C Exercises: Count the number of vowels and consonants

Secondary Nav

C Pointer : Exercise-13 with Solution

Write a program in C to count the number of vowels and consonants in a string using a pointer.
Test Data :
Input a string: string
Expected Output :

Number of vowels : 1                                                                                         
Number of constant : 5

C Code:

#include <stdio.h>
int main()
{
    char str1[50];
    char *pt;
    int  ctrV,ctrC;
 	printf("\n\n Pointer : Count the number of vowels and consonants :\n"); 
	printf("----------------------------------------------------------\n");	    
    printf(" Input a string: ");
    fgets(str1, sizeof str1, stdin);
     
    //assign address of str1 to pt
    pt=str1;
     
    ctrV=ctrC=0;
    while(*pt!='\0')
    {
        if(*pt=='A' ||*pt=='E' ||*pt=='I' ||*pt=='O' ||*pt=='U' ||*pt=='a' ||*pt=='e' ||*pt=='i' ||*pt=='o' ||*pt=='u')
            ctrV++;
        else
            ctrC++;
        pt++; //pointer is increasing for searching the next character
    }
     
    printf(" Number of vowels : %d\n Number of constant : %d\n",ctrV,ctrC);        
    return 0;
}

Flowchart :

Flowchart: Count the number of vowels and consonants

C Practice online:


#include <stdio.h>
int main()
{
    char str1[50];
    char *pt;
    int  ctrV,ctrC;
 	printf("\n\n Pointer : Count the number of vowels and consonants :\n"); 
	printf("----------------------------------------------------------\n");	    
    printf(" Input a string: ");
    fgets(str1, sizeof str1, stdin);
     
    //assign address of str1 to pt
    pt=str1;
     
    ctrV=ctrC=0;
    while(*pt!='\0')
    {
        if(*pt=='A' ||*pt=='E' ||*pt=='I' ||*pt=='O' ||*pt=='U' ||*pt=='a' ||*pt=='e' ||*pt=='i' ||*pt=='o' ||*pt=='u')
            ctrV++;
        else
            ctrC++;
        pt++; //pointer is increasing for searching the next character
    }
     
    printf(" Number of vowels : %d\n Number of constant : %d\n",ctrV,ctrC);        
    return 0;
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number