Tuesday, March 31, 2015

Specific character count in a word --- for loop and do while loop

Script

// Ask the user to input a word that has a minimum of 8 characters
// Ask the user to type in a specific character
// Print out the number of occurrences of that specific character in the word

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

main()
{
        string word = "";

        do
        {
        cout << "Enter a word that has 8 or more characters:  ";
        cin >> word;
        }
        while (word.size() < 8);

        char searchCharacter = '0';
        cout << "Enter a specific character and the program will count the number of occurrences of that letter in the word:  ";
        cin >> searchCharacter;

        int i=0;
        int counter = 0;
        for (i=0; i < word.size(); i++)
        {
        char specific = word.at(i);
        if (searchCharacter == specific)
        counter++;
        }

        cout << "The number of occurrences of the character " << searchCharacter << " in the word " << word << " is " << counter << "." << endl ;

}


Execution

Enter a word that has 8 or more characters:  Fluorescent
Enter a specific character and the program will count the number of occurrences of that letter in the word:  e
The number of occurrences of the character e in the word Fluorescent is 2.



Enter a word that has 8 or more characters:  Eagle
Enter a word that has 8 or more characters:  Cheetah
Enter a word that has 8 or more characters:  Enlightenment
Enter a specific character and the program will count the number of occurrences of that letter in the word:  t
The number of occurrences of the character t in the word Enlightenment is 2.



Enter a word that has 8 or more characters:  Counter-intuitive
Enter a specific character and the program will count the number of occurrences of that letter in the word:  i
The number of occurrences of the character i in the word Counter-intuitive is 3.



Enter a word that has 8 or more characters:  Extravagance
Enter a specific character and the program will count the number of occurrences of that letter in the word:  a
The number of occurrences of the character a in the word Extravagance is 3.



No comments:

Post a Comment