C++ Practice Assignment #6 - Letter Counter

In this C++ practice assignment, the task is to write a program that the user will enter in a word and then prompt the user to enter in a letter. It will then count the number of times the letter appears in the word that was previously entered in and display the result.

Algorithm of the Letter counter program

  1. Prompt user for a word
  2. The word will be displayed
  3. Prompt the user for a letter
  4. Count the number of times a letter appears in the word
  5. Display the result

This letter counting assignment would be applying the concepts of functions and control structures. The functions would allow us to write user defined functions for different parts of the program. The control structure as a for loop would be able to count through and match the total counted value found in the word quickly.


//-------------------------------------------------
// Letter Counter program
// Programmed in Visual Studio 2012
//-------------------------------------------------

#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>

using namespace std;

string word_input;
char c;

void word_input_func()
{
// Prompt the user for a word
cout << "Enter in a word less than 20 character long\n";
getline(cin, word_input);

cout << word_input;
cout << "\n";
}

int word_count_func()
{
char c;

int count = 0;
cout << "Enter in a letter to find in the word\n";
cin >> c;

cout << "\n";

for(int i = 0; i < word_input.length(); i++)
{
if(word_input[i] == c)
{
count++;
}
}

// Display total counted value
cout << "Total count in the word " << count << "\n";

return count;

}

int main()
{
word_input_func();
word_count_func();
}

Share this post