This is a C# Program to count number of vowels and consonants from a given string.
This C# Program Counts number of Vowels and consonants from a given String.
Here program is used to find the number of vowels and consonants present in the given sentence. The vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’, The remaining letters are consonants.
Here is source code of the C# Program to Count number of Vowels and consonants from a given String. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/* * C# Program to Count number of Vowels and consonants from a given String */ using System; class program { public static void Main() { char[] sentence = new char[100]; int i, vowels = 0, consonants = 0, special = 0, n; Console.WriteLine("Enter the Length of the sentence \n"); n = int.Parse(Console.ReadLine()); for (i = 0; i < n; i++) { sentence[i] = Convert.ToChar(Console.Read()); } for (i = 0; sentence[i] != '\0'; i++) { if ((sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u') || (sentence[i] == 'A' || sentence[i] == 'E' || sentence[i] == 'I' || sentence[i] == 'O' || sentence[i] == 'U')) { vowels = vowels + 1; } else { consonants = consonants + 1; } if (sentence[i] == 't' || sentence[i] == '\0' || sentence[i] == ' ') { special = special + 1; } } consonants = consonants - special; Console.WriteLine("No. of vowels {0}", vowels); Console.WriteLine("No. of consonants {0}", consonants); Console.ReadLine(); Console.ReadLine(); } }
In this C# program, we are reading the length of the sentence using ‘n’ variable. Using for loop convert the string to each character using sentence[] array variable. The vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’, the remaining letters are consonants. For loop is used to count the number of vowels, consonants and special characters present in the string.
If else condition statement is used to check the value of ‘i’ variable is equal to vowel characters lower case or upper case using Logical OR operators. If the condition is true then execute the statement and increment the value of ‘vowels’ variable by one. Otherwise, if the condition is false then execute the else statement and increment the value of ‘consonants’ variable by one.
Otherwise, if the condition is false then execute the else statement. Check the string present in the sentence has special character using Logical OR operators. If the condition is true then execute the statement and increment the value of ‘special’ variable by 1. Print the number of vowels and consonants in the string.
Enter the Length of the sentence 3 san No. of vowels 1 No. of consonants 2
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
- Practice MCA MCQs
- Check MCA Books
- Apply for Computer Science Internship
- Check C# Books
- Apply for C# Internship