Question

In C++, Write two programs to count the number of consonants in a string. One will...

In C++,

Write two programs to count the number of consonants in a string. One will use an iterative method and one will use a recursive method.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

ANSWER:-

(1) iterative method :-

#include <iostream>
using namespace std;
int totalConsonants(string str)
{
int count = 0;
char ch;
for (int i = 0; i < str.length(); i++)
{
   ch=str[i];
   ch = toupper(ch);
if(!(ch == 'A' || ch == 'E' ||
ch == 'I' || ch == 'O' ||
ch == 'U') && ch >= 65 && ch <= 90)
++count;
}
return count;
}
int main()
{
string str;
cout<<"Enter astring : abcdef\n";
cin>>str;
cout <<"the total consonants : "<<totalConsonants(str);
return 0;
}

(2) recursive method :-

#include <iostream>
using namespace std;
bool isConsonant(char ch)
{
ch = toupper(ch);
  
return !(ch == 'A' || ch == 'E' ||
ch == 'I' || ch == 'O' ||
ch == 'U') && ch >= 65 && ch <= 90;
}
// to count total number of consonants from
// 0 to n-1
int totalConsonants(string str, int n)
{
if (n == 1)
return isConsonant(str[0]);
  
return totalConsonants(str, n - 1) +
isConsonant(str[n-1]);
}
int main()
{
string str;
cout<<"Enter astring : abcdef\n";
cin>>str;
cout <<"the total consonants : "<<totalConsonants(str, str.length());
return 0;
}

// OUTPUT

// If any doubt please comment

Add a comment
Know the answer?
Add Answer to:
In C++, Write two programs to count the number of consonants in a string. One will...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT