Schedule‎ > ‎

Assignment 7 Programs with Functions


Objectives

  • Use a loop to iterate over all the characters in a string
  • Test user input for errors
  • Write simple functions
  • Use parameters to send data to functions.
  • Code return statements to return values from functions
  • Start to use functions to organize program code


Academic Honesty

Read the Scholastic Honesty Policy and Assignment Integrity policies of the syllabus. Here are some clarifications for this particular assignment:

  • Most importantly,  you undermine your own self confidence when you cheat,  because you know you didn't accomplish the assignment without cheating.
  • You may not give/show/post a copy of your code to anyone else.
  • You may not look at another student's code until you complete and submit this assignment.
  • You may get help from other people but only if they do not show or tell you the code to type.
  • Remember that the instructor performs similarity tests on programming project submissions, and copied or plagiarized code is usually very easy to detect.


Grading Criteria 

For each part: 10 pts: File Header 1pt, Function Headers 1pt, Compiles 2pts, Proper Formatting 1pt, Works as Specified 5pts

  1. funwork.cpp (10pts)
  2. charcount.cpp (10pts)
  3. toys.cpp (10pts)
  4. Extra Credit: xcfunwork.cpp (3pts)
Total Possible: 30 pts + Extra Credit 3pts


Project Specifications

Your solutions to these projects must only use techniques we have covered so far.

Programming Style

For all programs, remember to follow all the style rules we covered including the recent items:

  1. Program header and function headers are required.
  2. Avoid duplicating code (see textbook page 208)
  3. Function naming conventions (See: Function Names)
  4. Indentation in functions and placement of curly braces (See: Indentation)
  5. No magic numbers. (Hint: make arrays of numbers const)
  6. Indentation in while statements and placement of curly braces
  7. No tab characters in your code.

    You can remove tab characters by either setting up Notepad++ correctly (see here) or by running a program named astyle (see here).

  8. Meaningful variable names and consistent naming style (caps vs. underbars)..


Project 1: Function Worksheet

Functions are an important part of programming, allowing us to break up long sequences of code into shorter reusable parts. We then assemble the parts to create larger programs.

In this project we complete several functions. Each function is like a smaller program inside of a our larger program. Notice that we can focus on each function separately, allowing our full attention on each part of the problem.

functions
Project Specifications
  1. Start by downloading the worksheet: funwork.cpp.

    Keep the same filename and add to the existing code to complete the project. Leave the existing code unchanged, except for comments as instructed.

  2. Add your name and the date to the file comment block at the top of the file where shown in the comments.
  3. No user input is required for this project and do not add any.
  4. Write the required functions as described by the function signature and comments.
  5. Compile and run the code when finished with each function to see to verify correctness.

    Check the test results and make any alterations to your functions as necessary.

  6. When all of the tests pass, upload your completed source code file with the rest of the assignment to Canvas Assignment 7.


Project 2: Counting Characters

A personal name, or full name, refers to the set of names by which an individual is known and that can be recited as a word-group, with the understanding that, taken together, they all relate to that one individual.

For this project, you will ask the user to enter a word or phrase and then count the numbers of letters in the input that match the unique letters of your name, excluding spaces. If you have two or more letters in you name that are the same, only test for one of the letters. For example, if your name is "Jesus Roche" and the user enters "Egg Roll" the program will report a count of three (3) letters.  

Character Counts!
Project Specifications
  1. Write a program that prints the number of characters that match your personal name (full name)  from a word or phrase entered by a user. 
  2. You must name the source code file charcount.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Ask the user to enter a word or phrase, and no other input, as shown in the Example Run. Ask for all user input in the main() function and exit the program when the user enters a single letter "x" (without the quotes).
  4. Write a function with the following signature exactly:
    /**
        Counts the number of letters in str that match the unique letters
        (not spaces) of my name. However, the input string may have duplicate
        letters that are counted.
    
        @param str a string with a word or phrase
        @return the number of letters.
    */
    int countLetters(string str)
    

    When called, the function counts the number of letters in str that match unique characters in your name, both upper and lower case, and returns that count. For example, John has four unique characters in his name while Jojo has two unique characters. Thus entering "JJ" would return 2 characters for John and 2 for Jojo. Do NOT change the function's name, parameter type, number of parameters, or return type. Instead, pay attention to the intent of these items to guide your code development. Do not use tolower()toupper() or other techniques we have not covered.

  5. After calling the function, display the returned count of characters in the main() function.
  6. Add a while or do-while statement in main() that allows the user to repeat the program until the user enters a single "x" (without the quotes).

    Do NOT forget to include a getline() statement inside the loop.

  7. Example Run: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. Your program must count the characters for the set of names by which you are known to the instructor (like in feedback on previous assignments) and include your first and last names at a minimum.
    Enter a word or phrase (x to exit): Egg Roll
    The input contains 2 letters of your name.
    
    Enter a word or phrase (x to exit): eeee
    The input contains 4 letters of your name.
    
    Enter a word or phrase (x to exit): Ed Parrish
    The input contains 9 letters of your name.
    
    Enter a word or phrase (x to exit): The quick brown fox jumps over the lazy dog
    
    The input contains 12 letters of your name.
    
    Enter a word or phrase (x to exit): 12345
    The input contains 0 letters of your name.
    
    Enter a word or phrase (x to exit): x
    
    You have a name we can count on!
    

    In the above example run, the programmer's name is "Ed Parrish". Notice that the count is based on what the user entered and ignores duplicate characters in the programmer's name. The user entered the phrase shown in italics (for emphasis) to produce the output. Your program does NOT print the characters in italics, nor does the user input appear in italics.

  8. Submit this project with the rest of the assignment in Canvas.
Hints:
  • Iterate through each character of the input string with a for-loop like we discussed in lesson 6.2.3: Iterating Strings.
  • Inside the loop, use if-statements to test for each character of your name.  You can use a doubly nested loop.
  • To convert a character between upper and lower case, remember how the ASCII table is organized. The character 'A' is 65 and 'a' is 97. The difference between the two is 32. As an example, if a character is less than 'a' you can convert it to lower case by adding 32.
References and More Information
  1. Personal name: Wikipedia



Project 3: Buying the Most Toys

We know a young child who likes toys. We want to buy the child the most toys we can to make the biggest impression! However, we only have a certain amount of money we can spend. We are looking at a list of toy prices and we want to maximize the number of toys that we can buy without going over your budget.

To help us make the decision, we write a C++ program that tells us how many toys we can buy on the list with the amount of money we can spend.

Project Specifications
  1. Write a program that tells us the most individual toys we can buy from a list of prices, without duplicating any toy and without going over budget.
  2. Name the source code file toys.cpp and include all your code in this single file.

    Be careful of the spelling, including capitalization, as you will lose points for a misspelled name. Naming is important in programming.

  3. Ask the user for the amount of money to spend, and no other input, as shown in the Example Run.                                                                            



    Source: designed by Freepik

  4. Define a constant array with the following prices in your program.
    1.99, 2.49, 3.98, 4.99, 5.49, 6.98, 7.99, 10.75
    

    Make sure to add the prices to the array in the same order as given above.

  5. Define a function to count the number of toys we can buy for a given amount of money. Call the toy-counting function from the main() function.
  6. Add a while or do-while loop to main() that asks for the amount of money to spend indefinitely until the users enters an amount of money less than or equal to zero.
  7. Example Run: The input prompts and outputs of the program must look like the following for full credit, including the same order of input and wording of the output. For the input shown you must get the same output. However, the output must change properly if the inputs are different.
    ** Toy Maximizer! **
    
    Enter the amount of money to spend: 20
    Number of toys: 5
    Money remaining: 1.06
    
    Enter the amount of money to spend: 30
    Number of toys: 6
    Money remaining: 4.08
    
    Enter the amount of money to spend: 0
    You're the best!
    

    In the above example run, the user entered the values shown in italics (for emphasis) to produce the output. Your program does NOT print the characters in italics, nor does the user input appear in italics.

  8. Submit the source code file toys.cpp with the rest of this Assignment in Canvas.
Hints:
  • Print the number of toys inside the toy-counting function (spec 5). We may use cout in any function.
  • To avoid magic numbers with the array of prices, put const in front of the array.


Extra Credit 

The following are worth extra credit points (3 pts)

  1. Create your own interesting function problem for the function worksheet. (1 point for completing, 1 point for robust test cases, and 1 point for interest and creativity)
    1. Submit the extra function and its main() function in a file named xcfunwork.cpp.
    2. Do not have any user input in the extra credit file.
    3. Label the tests in main() with a cout statement with the words "Testing Extra Credit" followed by the function name, like:
      *** Testing Extra Credit myFabFun ***
      
    4. Following the label, include at least 3 test cases calling the extra function in main(), testing different aspects like the test cases in the standard project.

SOLUTION CODE:
Project 1:  funwork.cpp

/**
    CS-11 Asn 7, funwork.cpp
    Purpose: Practice writing functions and tests.

    @author Sharon Strelitz
    @version 1.0    02/20/2018
*/
#include <iostream>
using namespace std;

/**
    Given two int values, return their sum; unless the two values are the same,
    then return double their sum.
    @param a The first value to test.
    @param b The second value to test.

    Test cases:
    sumDouble(1, 2) ? 3
    sumDouble(3, 2) ? 5
    sumDouble(2, 2) ? 8
*/
int sumDouble(int a, int b)
{
    int sum = a + b;
    if (a == b)  {
        return sum * 2;
    }   else  {
        return sum;   
    }
}

/**
    Given 2 ints, a and b, return true if one of them is 10 or if their sum
    is 10.
    @param a The first value to test.
    @param b The second value to test.

    Test cases:
    makes10(9, 10) ? true
    makes10(9, 9) ? false
    makes10(1, 9) ? true
*/
bool makes10(int a, int b)
{
    if (a == 10 || b == 10) {
        return true;
    }  else if (a + b == 10) {
        return true;
    }  else {
        return false;
    }
}

/*
    We have two monkeys, a and b, and the parameters aSmile and bSmile indicate
    if each is smiling. We are in trouble if they are both smiling or if
    neither of them is smiling. Return true if we are in trouble.
    @param aSmile Set true if monkey a is smiling; else set false.
    @param bSmile Set true if monkey b is smiling; else set false.

    Test cases:
    monkeyTrouble(true, true) ? true
    monkeyTrouble(false, false) ? true
    monkeyTrouble(true, false) ? false
*/
bool monkeyTrouble(bool aSmile, bool bSmile)
{
    if ((aSmile && bSmile) || (!aSmile && !bSmile)) {
        return true;
    }   else  {
        return false;
    }
}

/**
    Return true if the given non-negative number is a multiple of 3 or a
    multiple of 5. Use the % "modulus" operator.
    @param num The value to test.

    Test cases:
    or35(3) ? true
    or35(10) ? true
    or35(8) ? false
*/
bool or35(int num)
{
    if (num%3 == 0|| num % 5 == 0) {
        return true;
    }  else  {
        return false;
    }
}

/**
    Given a string, return a new string where "not " has been added to the
    front. However, if the string already begins with "not", return the string
    unchanged.
    @param str The string to test and modify.

    Test cases:
    notString("candy") ? "not candy"
    notString("x") ? "not x"
    notString("not bad") ? "not bad"
*/
string notString(string str)
{
    string newString = "";
    if (str.substr(0,3) == "not") {
        return str;
    }  else  {
        newString = "not " + str;
        return newString;
    }
}

/**
    Return a new string where the first and last chars have been exchanged.
    @param str The string to modify.

    Test cases:
    frontBack("code") ? "eodc"
    frontBack("a") ? "a"
    frontBack("ab") ? "ba"
*/
string frontBack(string str)
{
    char first = str[0];
    char last = str[str.length() - 1];
    string newString = str;
    newString[0] = last;
    newString[str.length() - 1] = first;
    return newString;  
}

/**
    Given 3 int values, return true if 1 or more of them are teen.
    We'll say that a number is "teen" if it is in the range 13..19 inclusive.
    @param num1 The first number to test for teenness.
    @param num2 The second number to test for teenness.
    @param num3 The third number to test for teenness.

    Test cases:
    hasTeen(13, 20, 10) ? true
    hasTeen(20, 19, 10) ? true
    hasTeen(20, 10, 13) ? true
*/
bool hasTeen(int num1, int num2, int num3)
{
    if ( num1 >= 13 && num1 <= 19)  {
        return true;
    }  else if ( num2 >= 13 && num2 <= 19) {
        return true;
    }  else if ( num3 >= 13 && num3 <= 19) {
        return true;
    }  else  {
        return false;
    }
}

int main()
{
    const int TV3 = 3, TV8 = 8, TV9 = 9, TV10 = 10;
    const int TV13 = 13, TV19 = 19, TV20 = 20, TV45 = 45;
    int result;
    bool answer;
    string value;
    cout << boolalpha;
    cout << "*** Testing sumDouble ***"<< endl;
    result = sumDouble(1, 2);
    cout << "sumDouble1 should be 3: " << result << endl;
    result = sumDouble(TV3, 2);
    cout << "sumDouble2 should be 5: " << result <<endl;
    result = sumDouble(2, 2);
    cout << "sumDouble3 should be 8: " << result << endl;

    cout << "\n*** Testing makes10 ***"<< endl;
    answer = makes10(TV9, TV10);
    cout << "makes10a should be true: " << answer << endl;
    answer = makes10(TV9, TV9);
    cout << "makes10b should be false: " << answer << endl;
    answer = makes10(1, TV9);
    cout << "makes10c should be true: " << answer << endl;

    cout << "\n*** Testing monkeyTrouble ***"<< endl;
    answer = monkeyTrouble(true, true);
    cout << "monkeyTrouble1 should be true: " << answer << endl;
    answer = monkeyTrouble(false, false);
    cout << "monkeyTrouble2 should be true: " << answer << endl;
    answer = monkeyTrouble(true, false);
    cout << "monkeyTrouble3 should be false: " << answer << endl;

    cout << "\n*** Testing or35 ***"<< endl;
    answer = or35(TV3);
    cout << "or35a should be true: " << answer << endl;
    answer = or35(TV10);
    cout << "or35b should be true: " << answer << endl;
    answer = or35(TV8);
    cout << "or35c should be false: " << answer << endl;

    cout << "\n*** Testing notString ***"<< endl;
    value = notString("candy");
    cout << "notString1 should be not candy: " << value << endl;
    value = notString("x");
    cout << "notString2 should be not x: " << value << endl;
    value = notString("not bad");
    cout << "notString3 should be not bad: " << value << endl;

    cout << "\n*** Testing frontBack ***"<< endl;
    value = frontBack("code");
    cout << "frontBack1 should be eodc: " << value << endl;
    value = frontBack("a");
    cout << "frontBack2 should be a: " << value << endl;
    value = frontBack("ab");
    cout << "frontBack3 should be ba: " << value << endl;

    cout << "\n*** Testing hasTeen ***"<< endl;
    answer = hasTeen(TV13, TV20, TV10);
    cout << "hasTeen1 should be true: " << answer << endl;
    answer = hasTeen(TV20, TV19, TV10);
    cout << "hasTeen2 should be true: " << answer << endl;
    answer = hasTeen(TV20, TV10, TV13) ;
    cout << "hasTeen3 should be true: " << answer << endl;
    answer = hasTeen(TV20, TV10, TV45) ;
    cout << "hasTeen4 should be false: " << answer << endl;

    cout << "\n*** End of Tests ***" << endl;

    return 0;
}

PROJECT 2:  charcount.cpp (10pts)

/**
    CS-11 Asn 7 charcount.cpp
    Purpose: Counts the number of letters in a word the user enters that
             match the letters in my full name

    @author   Sharon Strelitz
    @version 1.0  02/15/2018
 */

#include <iostream>
using namespace std;
/**
    Counts the number of letters in str that match the unique letters
    (not spaces) of my name. However, the input string may have duplicate
    letters that are counted.  

    @param str a string with a word or phrase
    @return number of matches
*/
int countLetters(string str);

int main() {
    bool done = false;
    string userInput = "";
    while (!done) {
        cout << "\nEnter a word or phrase (x to exit): ";
        cin >> ws;     
        getline(cin, userInput);
        if (userInput[0] == 'x')  {
            cout << "You have a name we can count on!" << endl;
            done = true;
        }  else  {
             cout << "The input contains " << countLetters(userInput) << " letters of your name." << endl;
        }
    }
    return 0;
}

int countLetters(string str) {
    const int LOWER_CASE_BOUND = 97;
    const int CONVERT_CASE = 32;
    string myFullName = "Sharon Strelitz"; 
    int numLetters = 0;
    bool skip_this_space_outer = false;
    bool skip_this_space_inner = false;
    bool done_inner_loop = false;
    /*first loop through the input string looking for spaces (skip) 
    and uppercase (convert to lower)  */
    for (int i = 0; i < (int) str.length(); i++)  {
        skip_this_space_outer = false;    //reset from a previous loop
        done_inner_loop = false;          //reset from a previous loop
        if (str[i] == 32)  {  //space
            skip_this_space_outer = true;
        }  else if (str[i] < LOWER_CASE_BOUND) {  //uppercase
            str[i] += CONVERT_CASE;
        }  
        if (!skip_this_space_outer)  {
            /* loop through myFullname,  skipping spaces and convert to lowercase if needed
               then compare the input string char to myFullname. stop on first match
               now compare the input string to myFullName one char at a time  */
            for (int j = 0; j < (signed) myFullName.length() && !done_inner_loop; j++)  {
                skip_this_space_inner = false; //reset from previous loop
                done_inner_loop = false;      //reset from previous loop
                if (myFullName[j] == 32)  {  //space
                    skip_this_space_inner = true;
                }  else if (myFullName[j] < LOWER_CASE_BOUND) {  //uppercase
                    myFullName[j] += CONVERT_CASE;
                }  
                if (!skip_this_space_inner == true)  {
                    if (str[i] == myFullName[j])  { 
                        numLetters++;      
                        done_inner_loop = true;       //done counting this match (only unique matches)
                    } 
                }                
            }            
        }
    }
    return numLetters;
}

PROJECT 3  toys.cpp

/**
    CS-11 Asn 7, toys.cpp
    Purpose: Calculates the most individual toys we can buy
             from a list of prices without duplicating any toy 
             and without going over budget

    @author  Sharon Strelitz
    @version 1.0  01/21/2018
 */
#include <iostream>
#include <iomanip>
using namespace std;

/**
    function toycount:  counts the number of toys that we can buy for a
    given amount of money

    @param budget the amount of money we have to spend
    @param priceArray an array of toy prices
    @return the number of toys we can buy
*/
int toycount(double budget, const double priceArray[], const int arraySize)  {
    int count = 0;
    double moneyLeft = budget;
    for (int i = 0; i < arraySize; i++)  {
        if (priceArray[i] <= moneyLeft) {
            count++;
            moneyLeft -= priceArray[i];
        }       
    }
    cout << "Number of toys: " << count << endl;
    cout << fixed << setprecision(2);
    cout << "Money remaining: " << moneyLeft << endl;
     
    return count;
}

int main() {
    const int PRICE_ARRAY_SIZE = 8;
    const double toyPrices[] = {1.99, 2.49, 3.98, 4.99, 5.49, 6.98, 7.99, 10.75};
    double budget = 0.0;
    bool done = false;
    cout << "** Toy Maximizer!** " << endl << endl;
    while (!done)  {
        cout << "Enter the amount of money to spend (0 to stop): ";
        cin >> budget;
        if (budget > 0.0) {
            toycount(budget, toyPrices, PRICE_ARRAY_SIZE);
        }  else  {
            done = true;
        }
    }
    cout << "You're the best!" << endl;
    return 0;
}


Subpages (1): funwork.cpp
Comments