Count number of vowels in string

In this tutorial, we learn basic program which is to Count number of vowels in string.

What are the vowels?

In alphabets, as we know there are total 5 vowels and remaining are the consonant.

A logic for counting vowels in a string:

We take the counter to count vowels in a string. As we know what’s are the vowels based on that we check every character in a string for vowel if the character is vowel we increase counter value. After string encounters end we print the counter value as total vowels present in the string.

Algorithm to count number of vowels in a string:

  1. Start
  2. Declare a variable for string and counter variable.
  3. Take input string from the user.
  4. read character in string one by one.
  5. Write a condition to check character equals to a vowel.
  6. If condition is true, increment counter variable.
  7. String encounters end then stop.
  8. Now check for the counter variable value.
  9. If the counter value is zero, then no vowels present in the string.
  10. Else, print counter value as number of vowels present in string.
  11. Stop.

C program to count the number of vowels in string

1234567891011121314151617181920212223242526#include <stdio.h>#include<conio.h>void main (){   //declare variables    char s [10];    int i , cnt;     // take input string    printf (“Enter string “);    scanf (“%s”,&s);    // check for vowel    for (i=0; s [i] != ‘\0’; i++ )    {       if (s [i] == ‘A’ || s [i] == ‘a’ || s [i] ==’e’ || s [i] ==’E’ || s [i] ==’i’ || s [i] ==’I’ || s [i] ==’o’ || s [i]==’O’ || s [i] ==’u’ || s [i] ==’U’)       {          cnt ++;     }  }if (cnt == 0) {   printf (“\n No vowels in string “);{else {  printf (“\n Number of vowels in %s is %d”,s,cnt);}}

Output

C program to count the number of vowels in string

Explanation:

1) First, we declare variable.

char s [10] => for taking input string

int cnt => for counting the vowels

int i => for iterating in string

2) Take input string from the user. And store string in s.

Suppose input => technicalseek

s = technicalseek

3) Now actual logic starts ,

Read character from string one by one till end.

for (i=0; s [i] != ‘\0’; i++ )

4) In for after reading single character check whether character is vowel .

if (s [i] == ‘A’ || s [i] == ‘a’ || s [i] ==’e’ || s [i] ==’E’ || s [i] ==’i’ || s [i] ==’I’ || s [i] ==’o’ || s [i]==’O’ || s [i] ==’u’ || s [i] ==’U’)

5) If character is vowel , then increment cnt variable.

6) In our input .first we read t character then check for vowel it is not vowel so move to next character. Read second character e. Now it is vowel so cnt value incremented and now cnt = 1.

This continues till string ends.

7) After string encounters end.

s [i] == ‘\0’

8) Check cnt value .

9) If cnt ==0 , print no vowels in a string.

But in technicalseek we encountered vowels 5 times and cnt value is 5.

So , cnt =5 , Number of vowels in technicalseek is 5. Printed.

10) end