Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Saturday 23 January 2021

Program to Count Vowels and Consonants in a string

One of the popular programs which can be asked by the interviewer during the interview is to count no. of Vowels and Consonants in a string. The letters A, E, I, O, and U are called Vowels and the other letters (except vowels) in the alphabet are known as Consonants.

I will recommend you to check the below link for Top C# Interview Programs asked during the Interview and Examination.

In the below example, User will input the string which will be converted to lowercase so that comparison can be done without worrying about Upper-case or Lower-case characters. Then looping through each character of the string and check whether the character is in ‘a’, ’e’, ’I’, ’o’, and ‘u’. If yes, then increase the vowel counter value by 1. If the entered alphabet is between a to z but not in Vowels then need to increase Consonants variable value by 1. 
Program in C#:

Console.WriteLine("Count no. of Vowels and Consonants in a string");

//Variables to hold the Vowels and Consonants count

int vCount = 0;

int cCount = 0;

string inputString = string.Empty;

//Recieve the input from the user

inputString = Console.ReadLine();

//Lower the characters of the string for the comparision

inputString = inputString.ToLower();

//Loop through the each character of the string

for (int i = 0; i < inputString.Length; i++)

{

    //check and increase the counter if character is vowel

    if (inputString[i]=='a' || inputString[i]=='e' || inputString[i] == 'i' || inputString[i] == 'o' || inputString[i] == 'u')

    {

        vCount++;

    }

    //check and increase the counter if character is consonant

    else if (inputString[i]>='a' && inputString[i] <= 'z')

    {

        cCount++;

    }

}

//Showing the Vowels and Constants count in a string to the user

Console.WriteLine("Total no. of Vowels in a string=" + vCount);

Console.WriteLine("Total no. of Constants in a string=" + cCount);

Console.ReadLine();

Preview:
I hope this will help you in your interview preparation.
Thanks

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook