To solve the problem of counting vowels and consonants in a string, we need to understand a few basic concepts:

1. What are vowels and consonants?

  • Vowels: In the English language, the vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ (both uppercase and lowercase).
  • Consonants: Any other alphabetical characters apart from vowels are called consonants.

2. Steps to solve the problem:

  • Step 1: Take a string input from the user.
  • Step 2: Convert the string to lowercase (to avoid treating uppercase and lowercase letters differently).
  • Step 3: Check each character to see if it is a vowel or consonant. Ignore any non-alphabetic characters like numbers or punctuation marks.
  • Step 4: Count the vowels and consonants separately.
  • Step 5: Display the count of vowels and consonants.

Example

Let’s consider an example string:
Input: "Hello World!"

  • Vowels: ‘e’, ‘o’, ‘o’ → 3 vowels.
  • Consonants: ‘h’, ‘l’, ‘l’, ‘w’, ‘r’, ‘l’, ‘d’ → 7 consonants.
  • Non-alphabetic characters (like space and punctuation) are ignored.

Code Explanation in Multiple Languages

1. Python

def count_vowels_consonants(string):
    vowels = "aeiou"
    v_count = 0  # Vowel count
    c_count = 0  # Consonant count

    # Convert the string to lowercase
    string = string.lower()

    # Loop through each character in the string
    for char in string:
        if char.isalpha():  # Check if it's a letter
            if char in vowels:  # Check if it's a vowel
                v_count += 1
            else:
                c_count += 1  # It's a consonant if it's a letter but not a vowel

    return v_count, c_count

# Example usage
input_string = "Hello World!"
vowels, consonants = count_vowels_consonants(input_string)
print(f"Vowels: {vowels}, Consonants: {consonants}")
  • Explanation:
  • string.lower() ensures all characters are in lowercase.
  • We check if each character is alphabetic (char.isalpha()), then classify it as a vowel or consonant.
  • The function returns the number of vowels and consonants.
See also  How do you find the maximum element in an array?

2. JavaScript

function countVowelsConsonants(str) {
    const vowels = "aeiou";
    let vCount = 0;  // Vowel count
    let cCount = 0;  // Consonant count

    str = str.toLowerCase();  // Convert string to lowercase

    for (let char of str) {
        if (/[a-z]/.test(char)) {  // Check if it's a letter
            if (vowels.includes(char)) {
                vCount++;  // It's a vowel
            } else {
                cCount++;  // It's a consonant
            }
        }
    }

    return { vowels: vCount, consonants: cCount };
}

// Example usage
let inputString = "Hello World!";
let result = countVowelsConsonants(inputString);
console.log(`Vowels: ${result.vowels}, Consonants: ${result.consonants}`);
  • Explanation:
  • The regular expression /[a-z]/ ensures we only check alphabetic characters.
  • We use .includes() to check if a character is a vowel.

3. C++

#include <iostream>
#include <cctype>
using namespace std;

void countVowelsConsonants(string str) {
    string vowels = "aeiou";
    int v_count = 0, c_count = 0;

    // Convert string to lowercase
    for (int i = 0; i < str.length(); i++) {
        str[i] = tolower(str[i]);
    }

    // Loop through each character in the string
    for (char ch : str) {
        if (isalpha(ch)) {  // Check if it's a letter
            if (vowels.find(ch) != string::npos) {
                v_count++;  // It's a vowel
            } else {
                c_count++;  // It's a consonant
            }
        }
    }

    cout << "Vowels: " << v_count << ", Consonants: " << c_count << endl;
}

int main() {
    string input = "Hello World!";
    countVowelsConsonants(input);
    return 0;
}
  • Explanation:
  • We use tolower() to convert each character to lowercase.
  • isalpha() checks if a character is alphabetic, and find() checks if a character is a vowel.

4. Java

import java.util.Scanner;

public class VowelConsonantCounter {
    public static void main(String[] args) {
        String vowels = "aeiou";
        int vCount = 0, cCount = 0;

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = scanner.nextLine().toLowerCase();  // Convert to lowercase

        for (char ch : str.toCharArray()) {
            if (Character.isLetter(ch)) {  // Check if it's a letter
                if (vowels.indexOf(ch) != -1) {
                    vCount++;  // It's a vowel
                } else {
                    cCount++;  // It's a consonant
                }
            }
        }

        System.out.println("Vowels: " + vCount + ", Consonants: " + cCount);
    }
}
  • Explanation:
  • toLowerCase() ensures all characters are in lowercase.
  • We use Character.isLetter() to check if a character is alphabetic, and indexOf() to find vowels.
See also  HTML interview Question & their Solution

Summary of Steps:

  1. Take input and convert it to lowercase.
  2. Check each character:
  • If it’s a vowel, increase the vowel count.
  • If it’s a consonant, increase the consonant count.

3 . Display the results.

With these steps and code examples, the process of counting vowels and consonants should be clear. Each code example follows the same logic but is written in a different programming language.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *