Contact Learn C
Copy Program Share Program

Program 32:To Count number of vowels in a string

Program 32:
 
#include<stdio.h>
main()
{
 char s[100];
 int i,count=0;
 printf("Enter a string to know how many vowels are there \n");
 scanf("%s",&s);
 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')
   {
     count++;
   }
 }
 if(count==0)
 {
    printf("No vowels are there \n");
 }
 else
 {
    printf("Number of vowels in %s is %d\n",s,count);
 }
}
Explanation:
  1. The program starts with initializing :
    char s[100];
    int i,count=0;
    • s[100] → To store string input from user which can have 100 characters i.e. Letters
    • i → used as helping variable
    • count → To store count of characters in the input
  2. printf("Enter a string to know how many vowels are there \n");
    scanf("%s",&s);
    Taking string from user.While initializing we need to declare it as character Array but while taking input we can use %s to take string instead of %c.Where %s can take character array(many characters) as input at a time and %c can take single characters at a time.
  3. for(i=0;s[i]!='\0';i++)
    {
    The main logic starts from here.As the string given by us is a character array.As array count starts from zero.The for loop traverse from 0 to end of string(s[i]!='\0') where '\0' indicates end of string.So from given input Education(say) the loop traverse from E to n.
  4. 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')
    {
    count++;
    }
    Now each character is checked with the condition in 'if' part and if any character matches then the count is incremented by 1.For Example from input Education.Initially count=0.And || indicates OR Operation.
    • Iteration 1: E is checked with all characters in if condition as it matches with capital E the count becomes count=1.
    • Iteration 2: d is checked with all characters in if condition as it does not match with any character in if condition the count remains same so count=1
    • Iteration 3: u is checked with all characters in if condition as it matches with small u the count becomes count=2.
    • Similarly it continues with "cation" and count becomes 5
  5. if(count==0)
    {
    printf("No vowels are there \n");
    }
    else
    {
    printf("Number of vowels in %s is %d\n",s,count);
    }
    Now it checks whether the count is zero or not .If it is zero then printf in "if" part is executed otherwise the printf in else part which will print the number of vowels in the given string.


 Output:

Count number of vowels in a string

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide