Write a function int count_consonants(char str[]) that
determines and returns the number of consonants in a given
string.
Then write a simple main() function where you can repeatedly enter
a string and then the num- ber of consonants is determined and
printed on the screen (from the main() function). If the entered
string is empty (it will contain only a ’\n’ then) the program
should stop its execution. You can safely assume that the entered
string will be not longer than 100 characters and will be
valid.
Your solution has to satisfy the requirements from the problem description and has to pass the following testcase and potentially other testcases which are uploaded. All characters are relevant for passing testcases including newlines and spaces.
The explanation is clearly provided in the comments of the code itself.
CODE--
#include<bits/stdc++.h>
using namespace std;
int count_consonants(char str[])
{
//declare a variable to keep a count of the
consonants
int consonants=0;
//iterate over the str
int i=0;
while(str[i]!='\0')
{
//check for consonants
if(str[i]!='a' &&
str[i]!='e' && str[i]!='i' && str[i]!='o'
&& str[i]!='u' && str[i]!='A' &&
str[i]!='E' && str[i]!='I' && str[i]!='O'
&& str[i]!='U')
{
consonants++;
}
//increment iterator
i++;
}
//finally return the count
return consonants;
}
int main()
{
while(true)
{
char str[100];
//get input from the user
cout<<"Enter -1 to
exit\n";
cout<<"Enter a
string:\n";
cin.getline(str,100);
//check exit condition
if(str[0]=='-'&&str[1]=='1'&&str[2]=='\0')
{
cout<<"Thank You...!\n";
break;
}
//display the output
cout<<"Number of consonants =
"<<count_consonants(str)<<endl<<endl;
}
}
OUTPUT SCRENSHOT--
NOTE--
Please upvote if you like the effort.
Get Answers For Free
Most questions answered within 1 hours.