Knowee
Questions
Features
Study Tools

Write a program to accept a string as input and print the number of consonants in the string.Input:StringOutput:IntegerConstraints1<=length of string <=1000

Question

Write a program to accept a string as input and print the number of consonants in the string.Input:StringOutput:IntegerConstraints1<=length of string <=1000

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python program that accepts a string as input and prints the number of consonants in the string.

# Function to count the number of consonants in a string
def count_consonants(string):
    consonants = 0
    for i in range(len(string)):
        if string[i].isalpha(): # check if character is an alphabet
            if string[i] not in 'aeiouAEIOU': # check if alphabet is a consonant
                consonants += 1
    return consonants

# Accept string as input
string = input("Enter a string: ")

# Ensure string length is within constraints
if 1 <= len(string) <= 1000:
    print(count_consonants(string))
else:
    print("String length must be between 1 and 1000")

This program works by iterating over each character in the input string. If the character is an alphabet and it is not a vowel (i.e., it is a consonant), it increments the consonants counter. Finally, it prints the number of consonants in the string.

This problem has been solved

Similar Questions

Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158

find the number of alphabet vowels and words in input using string

Write a program in C to count the number of vowels and consonants in a string. You can use fgets to read the characters.

letter countWrite a C program that will analyze a line of text and will print the number of words, the number of consonants, and the number of vowels in the text.Testcase:Input:Programming is fun!Output:3      // Number of words:11   // Number of consonants:5   // Number of vowels:

IPS5-Pointer5Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.