Program to Count the Number of Vowels - (C# Basic Programs)
Counting the number of vowels in a given string is a common programming exercise that helps improve problem-solving skills. In this tutorial, we will discuss a program in C# to count the number of vowels in a given string.
Syntax
The syntax for counting the number of vowels in a string in C# is as follows:
int vowelCount = 0;
string input = "example string";
foreach (char c in input) {
if ("AEIOUaeiou".IndexOf(c) != -1) {
vowelCount++;
}
}
Console.WriteLine(vowelCount);
Example
using System;
namespace VowelCount
{
class Program
{
static void Main(string[] args)
{
int vowelCount = 0;
Console.WriteLine("Enter a string:");
string input = Console.ReadLine();
foreach(char c in input)
{
if("AEIOUaeiou".IndexOf(c)!=-1)
{
vowelCount++;
}
}
Console.WriteLine("Number of vowels: " + vowelCount);
}
}
}
Output:
Enter a string:
This is an example string
Number of vowels: 7
Explanation
The program uses a foreach loop to iterate through each character in the input string. It then checks if the character is a vowel by using the IndexOf()
method to see if the character exists in the string of vowels. If the character is a vowel, the vowel count is incremented. Finally, the program displays the number of vowels counted.
Use
Counting the number of vowels in a given string is a good exercise to improve C# programming skills. This program demonstrates the use of loops, conditional statements, and string manipulation to perform a useful task.
Summary
In this tutorial, we discussed a program in C# to count the number of vowels in a given string. We covered the syntax, example, explanation, and use of counting vowels in C#. By practicing similar exercises, programmers can improve their problem-solving skills and become better equipped to tackle more complex programming challenges.