Saturday, April 29, 2017

Programming Challenge 10.14 - Word Separator

/* Word Separator - This program accepts as input a sentence in which
   all words are run together, but the first character of each word is
    uppercase. The sentence is converted to a string in which the words
    are separated by spaces and only the first word starts with an
    uppercase letter. For example the string "StopAndSmellTheRose."
    Would be converted to "Stop and smell the roses." */

#include "Utility.h"

/* Introduces the functionality of this program to the user */
void intro();

/* Asks the user if he or she wants to repeat the process,
    returns the decision */
char tryAgain();

/* Searches for uppercase characters in a sentence,
   inserts spaces to separate the words at that position */
void separator(string &);

/* Replaces uppercase characters in a sentence with
   their lowercase equivalents */
void senDecapitalizer(string &);

/* Replaces lowercase characters at the beginning of sentences
   with their uppercase equivalent */
void senCapitalizer(string &);

int main()
{
    int     firstRun = 1;
    char   again = ' ';
    string sentence = " ";

    do
    {
        if (firstRun)
        {
            intro();
            firstRun = 0;
        }
        else
        {
            cout << "\n\n\tWORD SEPARATOR\n\n";
        }

        cout << "\tEnter a sentence:\n\t";

        getline(cin, sentence);

        separator(sentence);
        senDecapitalizer(sentence);
        senCapitalizer(sentence);

        cout << "\n\tThis is your sentence, correctly formatted:\n\t";
        cout << sentence;

        again = tryAgain();

        if (again == 'N')
        {
            cout << "\n\tHave a nice day!\n\n";
        }

    } while (again == 'Y');
    pauseSystem();
    return 0;
}

/* **********************************************************
   Definition: intro

    This function introduces the basic functionality of this
    program to the user.
   ********************************************************** */

void intro()
{
    cout << "\n\tWORD SEPARATOR\n\n"
          << "\tEnter a sentence without spaces, each word starting with\n"
          << "\tan uppercase letter, and I will separate the words.\n"
          << "\tA sentence such as:\n\n"
          << "\t'ThisSentenceDoesNotContainAnySpaces'\n\n"
          << "\twill be formatted, to look like this:\n\n"
          << "\t'This Sentence Does Not Contain Any Spaces.'\n\n"
          << "\tYou can repeat this process as often as you like to,\n"
          << "\tas long as you enter 'y' when asked.\n\n";
}

/* **********************************************************
   Definition: tryAgain

    This function asks the user if he or she wishes to try
    again. This decision is returned.
   ********************************************************** */

char tryAgain()
{
    char again = ' ';

    cout << "\n\n\tDo you wish to try this again? ";
    cin >> again;
    cin.ignore();

    /* Input validation */
    while (toupper(again) != 'Y' && toupper(again) != 'N')
    {
        cout << "\n\tDo you wish to try this again? ";
        cin >> again;
        cin.ignore();
    }

    return toupper(again);
}

/* **********************************************************
   Definition: separator

    This function searches for the occurence of uppercase
    characters in a sentence. If found, a space is inserted to
    separate the characters.
   ********************************************************** */

void separator(string &sentence)
{
    for (unsigned int index = 1; index < sentence.length(); index++)
    {
        if (isupper(sentence[index]))
        {
            sentence.insert((index++), " ");
        }
    }
}

/* **********************************************************
   Definition: senDecapitalizer

   This function replaces all uppercase characters found in
    a sentence by their lowercase equivalent.
   ********************************************************** */

void senDecapitalizer(string &sentence)
{
    for (unsigned int index = 1; index < sentence.length(); index++)
    {
        if (!isupper(sentence[index]))
        {
            sentence[index+1] = tolower(sentence[index+1]);
        }
    }
}

/* **********************************************************
   Definition: senCapitalizer

   This function converts letters at the beginning of each
    sentence to their uppercase equivalents.
   ********************************************************** */

void senCapitalizer(string &sentence)
{
    bool            isDelim = false;

    for (unsigned int index = 0; index < sentence.length(); index++)
    {
        if (sentence.at(index) == '.' || sentence.at(index) == '!' ||
            sentence.at(index) == '?')
        {
            isDelim = false;
        }

        if (isalpha(sentence.at(index)) && isDelim == false)
        {
            isDelim = true;
            sentence.at(index) = toupper(sentence.at(index));
        }
    }
}

Example Output:





Friday, April 28, 2017

Programming Challenge 10.13 - Date Printer

/* Date Printer - This program reads a string from the user containing a
   date in the form mm/dd/yyyy. It prints the date in the form March 12,
    2014. */

#include "Utility.h"

/* Performs various checks to confirm validity of input,
    returns the result */
bool checkDate(string);

/* Determines the correct month name,
   returns the month name */
string months(int);

/* Inserts month, day and year into the date string,
   displays the date */
void printDate(string, int, int);

int main()
{
    int    month = 0,
             day = 0,
            year = 0;
    string date = " ";

    cout << "\n\tDATE PRINTER\n\n"
          << "\tEnter a date in the format 'mm/dd/yyyy' and I will\n"
          << "\tconvert and display it. For example, after entering\n"
          << "\t'01/12/2017', the output will be 'January 12, 2017.'\n\n"
          << "\tPlease enter a date: ";
    getline(cin, date);

    while (checkDate(date) == false)
    {
        if (checkDate(date) == false)
        {
            cout << "\n\tThe date entered is invalid.\n"
                  << "\tPlease enter a date: ";
            getline(cin, date);
        }
    }

    month = stoi(date.substr(0));
    day = stoi(date.substr(3));
    year = stoi(date.substr(6));

    date = months(month);
             printDate(date, day, year);

    pauseSystem();
    return 0;
}

/* **********************************************************
   Definition: checkDate

    This function performs the following checks on the string

        * Correct length of the date string (This is the only
          condition that immediately returns the result in case
          the validity check fails)
        * Existence of delimiting characters '/'
        * Correctness of month, day, year input
        * Determins whether the year is a leap year. Based on
          the result, the month and day input is validated once
          more.

    The result is returned.
   ********************************************************** */

bool checkDate(string date)
{

    bool validDate = true;
    bool isLeapYear = false;
    int  month = 0,
          day = 0,
          year = 0;
    char delimiter = '/';

    if (date.length() < 10)
    {
        return validDate = false;
    }

    if (date.at(2) != delimiter || date.at(5) != delimiter)
    {
        validDate = false;
    }

    month = stoi(date.substr(0));

    if (month < 1 || month > 12)
    {
        validDate = false;
    }
   
    day = stoi(date.substr(3));

    if (day < 1 || day > 31)
    {
        validDate = false;
    }

    year = stoi(date.substr(6));

    if (year < 1 || year > 2100)
    {
        validDate = false;
    }

    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
    {
        isLeapYear = true;
    }

    if (isLeapYear && month == 2 && day > 29)
    {
        validDate = false;
    }

    if (isLeapYear == false && month == 2 && day > 28)
    {
        validDate = false;
    }

    return validDate;
}

/* **********************************************************
   Definition: months

    This function determines the name of a month, based on the
    integer value passed to it. The name is returned.
   ********************************************************** */

string months(const int month)
{
    const string monthNames[12] = { "January", "February", "March",
                                              "April", "May", "June", "July",
                                              "August", "September", "October",
                                              "November", "December" };

    return monthNames[month-1];
}

/* **********************************************************
   Definition: printDate

    This function accepts a string and two int values as
    arguments. It inserts day and year into the date string,
    and displays the date.
   ********************************************************** */

void printDate(string date, int day, int year)
{
    date.insert(date.length(), " " + to_string(day) + ", " + to_string(year));

    cout << "\n\tYour date is: " << date << endl;
}

Example Output:




Thursday, April 27, 2017

Programming Challenge 10.12 - Password Verifier

/* Password Verifier - Imagine we are developing a software package that
    requires users to enter their own passwords. Our software requires that
    user's passwords meet the following criteria:
  
        * The password should be at least six characters long
        * The password should contain at least one uppercase
          and at least one lowercase letter
        * The password should have at least one digit

    This program asks for a password and then verifies that it meets the
    stated criteria. If it doesn't, the program displays a message telling
    the user why. */

#include "Utility.h"

/* Determines the length of password,
    returns the result */
bool checkLength(string);

/* Determines whether the password contains uppercase characters,
    returns the result */
bool containsUpper(string);

/* Determines whether the password contains lowercase characters,
    returns the result */
bool containsLower(string);

/* Determines whether the password contains digits,
    returns the result */
bool containsDigit(string);

int main()
{  
    int    numTries = 5;
    string passphrase = "moRioka9713";
    string password = " ";

    cout << "\n\tKaibun Game - Login\n"
          << "\t-------------------\n";

    do
    {
        cout << "\n\tPlease enter your password: ";
        getline(cin, password);

        if (password != passphrase)
        {
            if (checkLength(password) == false)
            {
                cout << "\n\tPassword length mismatch.\n";
            }

            if (containsUpper(password) == false)
            {
                cout << "\tPassword does not contain uppercase characters.\n";
            }

            if (containsLower(password) == false)
            {
                cout << "\tPassword does not contain lowercase characters.\n";
            }

            if (containsDigit(password) == false)
            {
                cout << "\tPassword does not contain digits.\n";
            }

            cout << "\n\tYou have " << (numTries -= 1) << " tries left\n";

            if (numTries == 0)
            {
                cout << "\n\tYour password could not be verified.\n"
                      << "\tNow closing this program ...";
            }
        }

        else if (password == passphrase)
        {
            cout << "\n\tYou have been verified successfully.\n";
        }
    } while (numTries > 0 && password != passphrase);

    pauseSystem();
    return 0;
}

/* **********************************************************
    Definition: checkLength

    This function verifies that the password is at least six
    characters long. The result is returned.
    ********************************************************** */

bool checkLength(string password)
{
    bool length = false;

    password.length() >= 6 ? length = true : length = false;

    return length;
}

/* **********************************************************
    Definition: containsUpper

    This function verifies that the password contains at least
    one uppercase character. The result is returned.
    ********************************************************** */

bool containsUpper(string password)
{
    bool isUpper = false;

    for (size_t i = 0; i < password.length(); i++)
    {
        if (isupper(password[i]))
        {
            isUpper = true;
        }
    }

    return isUpper;
}

/* **********************************************************
    Definition: containsLower

    This function verifies that the password contains at least
    one lowercase character. The result is returned.
    ********************************************************** */

bool containsLower(string password)
{
    bool isLower = false;

    for (size_t i = 0; i < password.length(); i++)
    {
        if (islower(password[i]))
        {
            isLower = true;
        }
    }

    return isLower;
}

/* **********************************************************
    Definition: containsDigit

    This function determines whether the password contains any
    digits. The result is returned.
    ********************************************************** */

bool containsDigit(string password)
{
    bool isDigit = false;

    for (size_t i = 0; i < password.length(); i++)
    {
        if (isdigit(password[i]))
        {
            isDigit = true;
        }
    }

    return isDigit;
}

Example Output:




Tuesday, April 25, 2017

Programming Challenge 10.11 - Case Manipulator

/* Case Manipulator - This program contains three functions, upper, lower,
    and reverse.

    * The upper function accepts a pointer to a C-string as an argument.
      It steps through each character in the string, converting it to
      uppercase.

    * The lower function, too, accepts a pointer to a C-string as an
      argument. It steps through each character in the string, converting
      it to lowercase.

    * Like upper and lower, reverse accepts a pointer to a C-string. As it
      steps through the string, it tests each character to determine
      whether it is upper- or lowercase. If a character is uppercase, it
      is converted to lowercase. Likewise, if a character is lowercase,
      it is converted to uppercase.

    The functions are tested by asking for a string in function main, then
    passing it to them in the order: reverse, lower, and upper.    */

#include "Utility.h"

/* Determines character casing, changing upper- to lowercase letters
   and vice versa */
void reverse(char *);

/* Converts all characters from upper- to lowercase */
void lowercase(char *);

/* Converts all characters from lower- to uppercase */
void uppercase(char *);

int main()
{
    const int MAX_CHARS = 501;
    char         sentence[MAX_CHARS];

    cout << "\n\tCASE MANIPULATOR\n\n\t"
          << "Enter a sentence, " << (MAX_CHARS - 1)
          << " characters in length, and I will\n\t"
          << "first reverse all upper and lowercase characters, then\n\t"
          << "I will change all characters to lowercase, and lastly I\n\t"
          << "will change all characters to uppercase.\n\n";

    cout << "\n\tPlease enter your sentence:\n\t";
    cin.getline(sentence, MAX_CHARS);

    cout << "\n\n\tCHARACTER CASE REVERSAL\n";
    reverse(sentence);

    cout << "\n\tAll character cases have been reversed:\n"
          << "\t" << sentence << "\n\n";

    cout << "\n\tCHARACTERS TO LOWERCASE:\n";
    lowercase(sentence);

    cout << "\n\tAll uppercase characters have been changed "
          << "to lowercase:\n"
          << "\t" << sentence << "\n\n";
   
    cout << "\n\tCHARACTERS TO UPPERCASE:\n";
    uppercase(sentence);

    cout << "\n\tAll lowercase characters have been changed "
          << "to uppercase:\n"
          << "\t" << sentence << "\n\n";

    pauseSystem();
    return 0;
}

/* **********************************************************
   Definition: reverse

    This function accepts a pointer to a C-string as argument.
    It reverses all upercase characters to lowercase and vice
    versa.
   ********************************************************** */

void reverse(char *senPtr)
{
    for (size_t index = 0; senPtr[index] != '\0'; index++)
    {
        if (isupper(senPtr[index]))
        {
            senPtr[index] = tolower(senPtr[index]);
        }
       
        else if (islower(senPtr[index]))
        {
            senPtr[index] = toupper(senPtr[index]);
        }
    }
}

/* **********************************************************
    Definition: lowercase

    This function accepts a pointer to a C-string as argument.
    It converts all characters from upper- to lowercase.
    ********************************************************** */

void lowercase(char *senPtr)
{
    for (size_t index = 0; senPtr[index] != '\0'; index++)
    {
        if (isupper(senPtr[index]))
        {
            senPtr[index] = tolower(senPtr[index]);
        }
    }
}

/* **********************************************************
   Definition: uppercase

    This function accepts a pointer to a C-string as argument.
    It converts all characters from lower- to uppercase.
   ********************************************************** */

void uppercase(char *senPtr)
{
    for (size_t index = 0; senPtr[index] != '\0'; index++)
    {
        if (islower(senPtr[index]))
        {
            senPtr[index] = toupper(senPtr[index]);
        }
    }
}

Example Output:



Monday, April 24, 2017

Programming Challenge 10.10 - Replace Substring Function

/* Replace Substring Function - This program contains a function called
    replaceSubstring. It accepts three string objects as arguments. It
    searches string1 for all occurrences in string2. When it finds an
    occurrence of string2, it replaces it with string3. For example,
    suppose the three arguments have the following values:
  
        * string1:        "the dog jumped over the fence"
        * string2:        "the"
        * string3:        "that"

    With these three arguments, the function returns a string object
    with the value "that dog jumped over the fence." */

#include "Utility.h"

/* Asks the user if he or she wants to repeat the process,
    returns the decision */
char tryAgain();

/* Introduces the functionality of this program to the user */
void intro();

/* Decapitalizes the first character in a sentence */
void senDecapitalizer(string &, string &);

/* Capitalizes the first character at the beginning of each sentence */
void senCapitalizer(string &);

/* Searches for all occurrences of a word entered by the user in a
    sentence, replaces this word, returns a string object which
    contains the new sentence */
string replaceSubstring(const string, const string, const string);

int main()
{
    int     firstRun = 1;
    char     again = ' ';
    string sentence = " ";
    string searchWord = " ";
    string replaceWord = " ";
    string altered = " ";

    do
    {
        if (firstRun)
        {
            intro();
            firstRun = 0;
        }
        else
        {
            cout << "\n\n\tWORD REPLACER\n\n";
        }

        cout << "\n\tEnter a sentence: ";
        getline(cin, sentence);

        cout << "\n\tThis is your original sentence:\n\t"
              << sentence;

        cout << "\n\n\tEnter a word to search for: ";
        getline(cin, searchWord);

        senDecapitalizer(sentence, searchWord);

        cout << "\n\tEnter a word to replace the "
              << "\'" << searchWord << "\' with: ";
        getline(cin, replaceWord);

        altered = replaceSubstring(sentence, searchWord, replaceWord);

        senCapitalizer(altered);

        cout << "\n\tThis is your altered sentence:\n"
              << "\t" << altered << " ";

        again = tryAgain();

        if (again == 'N')
        {
            cout << "\n\tHave a nice day!\n\n";
        }

    } while (again == 'Y');

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: intro

    This function introduces the basic functionality of this
    program to the user.
   ********************************************************** */

void intro()
{
    cout << "\n\tWORD REPLACER\n\n"
          << "\tThis program first asks you to enter a sentence, then\n"
          << "\tyou are asked to enter a word to be searched for. If the\n"
          << "\tword exists, you are asked to enter a word or words the\n"
          << "\tsearch word should be replaced with. For example, if this\n"
          << "\tis the sentence you entered:\n\n"
          << "\t'The quick brown fox jumped over the lazy dog.'\n\n"
          << "\tIf you search for 'the,' (without quotes), and the word to\n"
          << "\treplace 'the' is 'that', your sentence will be changed to:\n\n"
          << "\t'That quick brown fox jumped over that lazy dog.'\n\n"
          << "\tNote that the input is case-insensitive. You can enter a\n"
          << "\tsentence containing lowercase characters only, or a mixture\n"
          << "\tof both lower and uppercase characters. The same applies to\n"
          << "\tthe word to search for. In other words you can enter:\n\n"
          << "\t'THE', 'tHe' or simply 'the' if you wish to.\n\n"
          << "\tYou can repeat this process by entering 'y' or 'Y', when\n"
          << "\tasked.\n\n";
}

/* **********************************************************
   Definition: tryAgain

    This function asks the user if he or she wishes to try
    again. This decision is returned.
   ********************************************************** */

char tryAgain()
{
    char again = ' ';

    cout << "\n\n\tDo you wish to try this again? ";
    cin >> again;
    cin.ignore();

    /* Input validation */
    while (toupper(again) != 'Y' && toupper(again) != 'N')
    {
        cout << "\n\tDo you wish to try this again? ";
        cin >> again;
        cin.ignore();
    }

    return toupper(again);
}

/* **********************************************************
   Definition: senCapitalizer

   This function accepts two string class objects. If one or
    the other contains uppercase characters, they are changed
    to lowercase.
   ********************************************************** */

void senDecapitalizer(string &sentence, string &searchWord)
{
      for (unsigned int i = 0; i < sentence.length(); i++)
    {
        if (isupper(sentence[i]))
        {
            sentence[i] = tolower(sentence[i]);
        }
    }
}

/* **********************************************************
   Definition: replaceSubstring

    This function accepts three string objects as argument. It
    searches the original sentence for a string entered by the
    user, and if it is found, replaces the word or words. The
    altered sentence is returned.
   ********************************************************** */

string replaceSubstring(const string sentence, const string searchWord,
                                const string replaceWord)
{
    string altered = sentence;  
    size_t findWord = altered.find(searchWord);

    while (findWord != string::npos)
    {
        altered.replace(findWord, searchWord.size(), replaceWord);
        findWord = altered.find(searchWord, findWord + replaceWord.length());
    }

    return altered;
}

/* **********************************************************
   Definition: senCapitalizer

   This function accepts a string class object as argument.
   It capitalizes the first letter in each sentence.
   ********************************************************** */

void senCapitalizer(string &sentence)
{
    unsigned int index = 0;
    bool         isDelim = false;

    for (index = 0; index < sentence.length(); index++)
    {
        if (sentence.at(index) == '.' || sentence.at(index) == '!' ||
            sentence.at(index) == '?')
        {
            isDelim = false;
        }

        if (isalpha(sentence.at(index)) && isDelim == false)
        {
            isDelim = true;
            sentence.at(index) = toupper(sentence.at(index));
        }
    }
}

Example Output:






Sunday, April 23, 2017

Programming Challenge 10.9 - Most Frequent Character

/* Most Frequent Character - This program contains a function that accepts
    a string object as its argument. The function returns the character that
    appears most frequently in the string. */

#include "Utility.h"

/* Finds the most frequently occuring character in the string,
    stores the frequency in a reference variable, returns the
    most frequently occuring character */
char mostFreq(string, unsigned int &);

int main()
{
    unsigned int frequency = 0;
    char             mostFreqChar = ' ';    
    string         sentence = " ";
  
    cout << "\n\tMost Frequent Character\n\n"
          << "\tEnter a sentence, and I will show you, what the most\n"
          << "\tfrequently occuring character is.\n\n"
          << "\tPlease enter your sentence: ";
    getline(cin, sentence);

    mostFreqChar = mostFreq(sentence, frequency);

    cout << "\n\tThe most frequent character is "
          << '\'' << mostFreqChar << '\'' << ", appearing "
          << frequency << " times in your sentence.";

   pauseSystem();
   return 0;
}

/* **********************************************************
    Definition: mostFreq

    This function accepts a string class object as argument.
    It determines the most frequently appearing character in
    the string and returns it. The frequency in which this
    character appears is stored in a reference variable.
   ********************************************************** */

char mostFreq(string sentence, unsigned int &frequency)
{
    unsigned int index = 0,
                     startScan = 0,
                     charCount = 0;
    char             mostFreqChar = ' ';

    for (startScan = index + 1; startScan < sentence.size(); startScan++)
    {
        charCount = 0;

        for (index = 0; index < sentence.size(); index++)
        {
            if (isalpha(sentence[index]) && isalpha(sentence[startScan]))
            {
                if (tolower(sentence[startScan]) == tolower(sentence[index]))
                {
                    charCount++;
                }

                if (charCount > frequency)
                {
                    frequency = charCount;
                    mostFreqChar = (tolower(sentence[index]));
                }
            }
        }
    }

    return mostFreqChar;
}

Example Output:





Saturday, April 22, 2017

Programming Challenge 10.8 - Sum Of Digits

/* Sum Of Digits - This program asks the user to enter a series of
    single digit numbers with nothing separating them. The input is
    read as a string object. The program displays the sum of all the
    single-digit numbers in the string. For example, if the user enters
    2514, the program displays 12, which is the sum of 2, 5, 1, and 4.
    It also displays the highest and lowest digits in the string. */

#include "Utility.h"

/* Calculates the sum-total of numbers in a string class object,
    returns this number */
int sumOfNumbers(string);

/* Finds the smallest number in a string class object, returns
    this number */
int findLowest(string);

/* Finds the highest number in a string class object, returns
    this number */
int findHighest(string);

/* Asks the user if he or she wants to repeat the process,
    returns the decision */
char tryAgain();

int main()
{
    int     total = 0,
             lowestNum = 0,
             highestNum = 0;
    char   again = ' ';
    string numbers = " ";
   
    do
    {
        cout << "\n\n\t\tSUM OF DIGITS\n\n"
              << "\tEnter a series of numbers without spaces in between\n"
              << "\tand I will calculate the sum of numbers for you.\n\n\t"
              << "Please enter your numbers: ";
        getline(cin, numbers);

        cout << "\n\n\tThe sum of your numbers is: "
              << (total = sumOfNumbers(numbers)) << "\n\n\t";

        cout << "This is the lowest number found: " << setw(2) << right
              << (lowestNum = findLowest(numbers)) << "\n\t";

        cout << "This is the highest number found: "
              << (highestNum = findHighest(numbers)) << "\n\n\t";

        again = tryAgain();

        if (again == 'N')
        {
            cout << "\n\tHave a nice day!\n\n";
        }

    } while (again == 'Y');

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: sumOfNumbers

    This function accepts a string class object as argument.
    It calculates the sum of numbers in the string. The sum-
    total is returned.
   ********************************************************** */

int sumOfNumbers(string numbers)
{
    int total = 0;

    for (unsigned int index = 0; index < numbers.size(); index++)
    {
        total += numbers[index] - '0';
    }

    return total;
}

/* **********************************************************
   Definition: findLowest

    This function accepts a string class object as argument.
    It determines the lowest number and returns it.
   ********************************************************** */

int findLowest(string numbers)
{
    int lowestNum = numbers[0] - '0';

    for (unsigned int index = 0; index < numbers.size(); index++)
    {
        if (lowestNum > numbers[index] - '0')
        {
            lowestNum = numbers[index] - '0';
        }
    }

    return lowestNum;
}

/* **********************************************************
   Definition: findHighest

    This function accepts a string class object as argument.
    It determines the highest number in a string and returns
    it.
   ********************************************************** */

int findHighest(string numbers)
{
    int highestNum = numbers[0] - '0';

    for (unsigned int index = 0; index < numbers.size(); index++)
    {
        if (highestNum < numbers[index] - '0')
        {
            highestNum = numbers[index] - '0';
        }
    }

    return highestNum;
}

/* **********************************************************
   Definition: tryAgain

    This function asks the user if he or she wishes to try
    again. This decision is returned.
   ********************************************************** */

char tryAgain()
{
    char again = ' ';

    cout << "Do you wish to try this again? ";
    cin >> again;
    cin.ignore();

    /* Input validation */
    while (toupper(again) != 'Y' && toupper(again) != 'N')
    {
        cout << "Do you wish to try this again? ";
        cin >> again;
        cin.ignore();
    }

    return toupper(again);
}

Example Output:




Friday, April 21, 2017

Programming Challenge 10.7 - Name Arranger

/* Name Arranger - This program asks for the user's first, middle and
    last names. The names should be stored in three different character
    arrays. The program then stores, in a fourth array, the name arranged
    in the following manner:
   
        * The last name followed by a comma and a space, followed by the
          first name and a space, followed by the middle name.
         
    For example, if the user enters "Carol Lynn Smith", it stores "Smith,
    Carol Lynn" in the fourth array. The contents of the fourth array is
    displayed on the screen. */

#include "Utility.h"

/* Arranges the name in the order last, first, and middle name,
    stores it in an array, returns a pointer to the array */
char *nameArranger(const char *, const char *, const char *);

int main()
{
    const int NAME_SIZE = 30;

    char         firstName[NAME_SIZE],
                 middleName[NAME_SIZE],
                 lastName[NAME_SIZE];

    char        *fullName = " ";

    cout << "\n\tName Arranger\n\n"
          << "\tEnter your first name: ";
    cin.getline(firstName, NAME_SIZE);

    cout << "\n\tEnter your middle name: ";
    cin.getline(middleName, NAME_SIZE);

    cout << "\n\tEnter your last name: ";
    cin.getline(lastName, NAME_SIZE);

    cout << "\n\tYour full name, sorted in order of last-,\n\t"
              "first-, and middle name: "
          << (fullName = nameArranger(firstName, middleName, lastName))
          << "\n\n";

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: nameArranger

    This function accepts three pointers to C-string objects
    as argument. The names are concatenated and stored in a
    char array. A pointer to this array is returned.
   ********************************************************** */

char *nameArranger(const char *firstName, const char *middleName,
                         const char *lastName)
{
    const int MAX_CHARS = 50;
   
    char *fullName = new char[MAX_CHARS]();

    strcat_s(fullName, MAX_CHARS, lastName);
    strcat_s(fullName, MAX_CHARS, ", ");
    strcat_s(fullName, MAX_CHARS, firstName);
    strcat_s(fullName, MAX_CHARS, " ");
    strcat_s(fullName, MAX_CHARS, middleName);

    return fullName;
}

Example Output:



Wednesday, April 19, 2017

Programming Challenge 10.6 - Vowels And Consonants

/* Vowels And Consonants - This program contains a function that accepts
    a pointer to a C-string as its argument. The function counts the number
    of vowels appearing in the string and returns that number.
   
    The second function accepts a pointer to a C-string as its argument.
    It counts the number of consonants appearing in the string and returns
    that number.
   
    The functions are demonstrated by performing the following steps:

        * The user is asked to enter a string.

        * The program displays the following menu:

            * Count the number of vowels in the string
            * Count the number of consonants in the string
            * Count both the vowels and consonants in the string
            * Enter another string
            * Exit the program

        * The program performs the operation selected by the user and
          repeats until the user selects E to exit the program. */

#include "Utility.h"

/* Provides a basic menu */
int menu();

/* Allows the user to make a menu choice,
    returns the menu choice */
int menuOptions();

/* Determines whether a character is a vowel,
    returns the result */
bool vowel(char);

/* Counts the vowels in a C-string,
    returns the number of vowels found */
int countVowels(char *);

/* Counts the consonants in a C-string,
    returns the number of consonants found */
int countConsonants(char *);

int main()
{
    menu();

   pauseSystem();
   return 0;
}

/* **********************************************************
    Definition: menu

    This function provides a basic menu.
   ********************************************************** */

int menu()
{
    const int NUM_WORDS = 200;

    int         numVowels = 0,
                 numConsonants = 0,
                 menuChoice = 0;
    char         sentence[NUM_WORDS];

    cout << "\n\tVOWEL AND CONSONANT COUNT\n\n"
          << "\tEnter a sentence, " << (NUM_WORDS - 1)
          << " characters maximum in length:\n\t";
    cin.getline(sentence, NUM_WORDS);

    do
    {
        menuChoice = menuOptions();
        cin.ignore();

        switch (menuChoice)
        {
            case 1:
            {               
                cout << "\n\tYour sentence contains: "
                      << (numVowels = countVowels(sentence))
                      << " vowels.\n\n";
            }
            break;

            case 2:
            {
                cout << "\n\tYour sentence contains: "
                      << (numConsonants = countConsonants(sentence))
                      << " consonants.\n\n";
            }
            break;

            case 3:
            {
                cout << "\n\tYour sentence contains: "
                      << (numVowels = countVowels(sentence))
                      << " vowels and "
                      << (numConsonants = countConsonants(sentence))
                      << " consonants.\n\n";
            }
            break;

            case 4:
            {
                cout << "\n\tEnter another sentence:\n\t";
                cin.getline(sentence, NUM_WORDS);
            }
            break;

            case 5:
            {
                cout << "\n\tHave a nice day!\n\n";
            }
        }
    } while (menuChoice != 5);

    return 0;
}

/* **********************************************************
    Definition: displayOptions

    This function displays the main menu options.
   ********************************************************** */

int menuOptions()
{
    const int VOWEL_COUNT = 1,
                 CONSONANT_COUNT = 2,
                 VOWEL_CONSONANT_COUNT = 3,
                 AGAIN = 4,
                 EXIT = 5;

    int         menuChoice = 0;

    cout << "\n\tMain Menu\n"
          << "\t----------\n\n"
          << "\t1. Count the number of vowels in the string\n"
          << "\t2. Count the number of consonants in the string\n"
          << "\t3. Count both the vowels and consonants in the string\n"
          << "\t4. Enter another string\n"
          << "\t5. Exit\n\n"
          << "\tEnter your choice: ";
    cin >> menuChoice;

    /* Input validation */
    while (menuChoice < VOWEL_COUNT || menuChoice > EXIT)
    {
        cout << "\tEnter your choice: ";
        cin >> menuChoice;
    }

    return menuChoice;
}

/* **********************************************************
    Definition: isVowel

    This function determines if a character is a vowel. The
    result is returned.
   ********************************************************** */

bool vowel(char vowel)
{
    if (vowel == 'a' || vowel == 'i' || vowel == 'e' || vowel == 'o' ||
         vowel == 'u' || vowel == 'A' || vowel == 'I' || vowel == 'I' ||
         vowel == 'O' || vowel == 'U')
    {
        return true;
    }
    else
    {
        return false;
    }
}

/* **********************************************************
   Definition: countVowels

    This function accepts a C-string object as argument. It
    counts the number of vowels and returns this number.
   ********************************************************** */

int countVowels(char *wordPtr)
{
    unsigned int index = 0,
                     vowelCount = 0;

    for (index = 0; index < strlen(wordPtr); index++)
    {   
        if (vowel(wordPtr[index])==true)
        {   
            ++vowelCount;
        }       
    }

    return vowelCount;
}

/* **********************************************************
   Definition: countConsonants

    This function accepts a C-string object as argument. It
    counts the number of consonants in a sentence and returns
    this number.
   ********************************************************** */

int countConsonants(char *wordPtr)
{
    unsigned int index = 0,
                     consonantCount = 0;
    bool             isConsonant = false;

    for (index = 0; index < strlen(wordPtr); index++)
    {
        if (vowel(wordPtr[index]) == true)
        {
            isConsonant = false;
        }

        else if (isalpha(wordPtr[index]))
        {
            isConsonant = true;
            consonantCount++;
        }   
    }

    return consonantCount;
}

Example Output:









Tuesday, April 18, 2017

Programming Challenge 10.5 - Sentence Capitalizer

/* Sentence Capitalizer - This program contains a function that accepts
   a pointer to a C-String object as an argument. It capitalizes the
   first character of each sentence in the string. For instance, if the
   string argument is:
 
      * "hello. my name is Joe. what is your name?"
    
   the function manipulates the string so it contains:
 
      * "Hello. My name is Joe. What is your name?"
 
   This function is demonstrated by asking the user to input a string,
   which is passed to the function. The modified string is displayed
   on the screen.

   Optional Exercise: This program also contains an overloaded version
   of this function that accepts a string class object as its argument. */

#include "Utility.h"

/* Capitalizes the first letter of a word at the beginning of every
   sentence */
void senCapitalizer(char *);

/* Capitalizes the first letter of a word at the beginning of every
   sentence. */
void senCapitalizer(string &);

int main()
{
   const int  NUM_CHARS = 501;
   char          sentence[NUM_CHARS];
   string      ctrlSentence = " ";
 
   cout << "\n\tSENTENCE CAPITALIZER\n\n"
        << "\tEnter a sentence, " << (NUM_CHARS - 1)
        << " characters in length:\n\t";
       cin.getline(sentence, NUM_CHARS);

       cout << "\n\tCapitalizing the letters ...\n\n";
       senCapitalizer(sentence);

       cout << "\tThis is your sentence:\n";
       cout << "\t" << sentence;

       cout << "\n\n\tNow enter another sentence:\n\t";
       getline(cin, ctrlSentence);

       cout << "\n\n\tCapitalizing the letters ...\n\n";
       senCapitalizer(ctrlSentence);

       cout << "\tThis is your sentence:\n";
       cout << "\t" << ctrlSentence;

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: senCapitalizer

   This function accepts a pointer to a C-string object as
   argument. It capitalizes the first letter in each
   sentence.
   ********************************************************** */

void senCapitalizer(char *charPtr)
{
    unsigned int index = 0;
    bool         isDelim = false;

    for (index = 0; index < strlen(charPtr); index++)
    {
        if (charPtr[index] == '.' || charPtr[index] == '!' ||
            charPtr[index] == '?')
        {
            isDelim = false;
        }

        if (isalpha(charPtr[index]) && isDelim == false)
        {
            isDelim = true;
            charPtr[index] = toupper(charPtr[index]);
        }
    }
}

/* **********************************************************
   Definition: senCapitalizer

   This function accepts a string class object as argument.
   It capitalizes the first letter in each sentence.
   ********************************************************** */

void senCapitalizer(string &sentence)
{
    unsigned int index = 0;
    bool         isDelim = false;

    for (index = 0; index < sentence.length(); index++)
    {
        if (sentence.at(index) == '.' || sentence.at(index) == '!' ||
            sentence.at(index) == '?')
        {
            isDelim = false;
        }

        if (isalpha(sentence.at(index)) && isDelim == false)
        {
            isDelim = true;
            sentence.at(index) = toupper(sentence.at(index));
        }
    }
}

Example Output:






Thursday, April 13, 2017

Programming Challenge 10.4 - Average Number Of Letters

/* Average Number Of Letters - This program is a modification of
   Programming Challenge 10.3 It displays the average number of
   letters in each word. */

#include "Utility.h"

   /* Counts the letters and words contained in the string, returns
      the number of words*/
int countWords(char *, double &);

/* Overloaded function: Counts the letters and words in the string
   class object, returns the number of words */
int countWords(string, double &);

int main()
{
   const int NUM_WORDS = 501;
   int         numWords = 0;
   double     letterCount = 0.0,
             ctrlLetters = 0.0,
             average = 0.0;
   char         sentence[NUM_WORDS];
   string     ctrlSentence = " ";

   cout << "\n\tWORD COUNT - AVERAGE NUMBER OF LETTERS\n\n"
        << "\tEnter a sentence, " << (NUM_WORDS - 1)
        << " characters in length:\n\t";
   cin.getline(sentence, NUM_WORDS);

   cout << "\n\tYour sentence contains: "
        << (numWords = countWords(sentence, letterCount))
        << " words.";

   cout << fixed << setprecision(2);
   cout << "\n\tThe average number of characters is: "
      << (average = letterCount / numWords - 1) << "\n";

   cout << "\n\tEnter another sentence:\n\t";
   getline(cin, ctrlSentence);

   cout << "\n\tThis sentence contains: "
      << (numWords = countWords(ctrlSentence, ctrlLetters))
      << " words.";

   cout << "\n\tThe average number of characters is: "
        << (average = ctrlLetters / numWords);

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: countWords

   This function accepts a pointer to a C-string as argument.
   It determines the number of letters and stores this value
   in letterCount. It also counts the words contained in the
   sentence passed to the function and returns this number.
   ********************************************************** */

int countWords(char *wordPtr, double &letterCount)
{
   int            wordCount = 0;
   char            delimList[] = "\" ´-.()*=_!?~<<>>:,\t\n";
   char           *next_word = NULL;
   double        avg = 0.0;
   unsigned int count = 0;
  
   /* Get the letter count */
   while (count != strlen(wordPtr + 1))
   {
      if (!isascii(*wordPtr) && *delimList)
      {
         ++count;
      }
      else
      {
         ++letterCount;
      }
      count++;
   }

   wordPtr = strtok_s(wordPtr, delimList, &next_word);

   while (wordPtr != NULL)
   {     
       if (wordPtr != NULL)
      {     
          wordPtr = strtok_s(NULL, delimList, &next_word);
         ++wordCount;
      }
   }   

   return wordCount;
}

/* **********************************************************
   Definition: countWords

   This overloaded function accepts a string class object as
   argument. It counts the letters, the value is stored in
   letterCount. It also counts the number of words, which
   number is returned from the function.
   ********************************************************** */

int countWords(string ctrlString, double &letterCount)
{
   size_t wordCount = 0,
          numDelims = 0,
          count = 0;

   bool isDelim = true;

   for (size_t index = 0; index < ctrlString.length(); ++index)
   {
      /* If a delimiter or whitespace is found, numDelim increments,
      and isDelim(iter) gets true. Else a word is found, and
      wordCount increments. */
      if (isspace(ctrlString[index]) || ispunct(ctrlString[index]))
      {
         numDelims++;
         isDelim = true;
      }
      else if (isDelim && !ispunct(ctrlString[index + 1]))
      {
         isDelim = false;
         ++wordCount;
      }
   }

   /* Counts the number of letters */
   while (count < ctrlString.length())
   {
      if (isalpha(ctrlString[count]))
         ++letterCount;

      count++;
   }

   return wordCount;
}

Example Output: