Schedule‎ > ‎

Assignment 8 Multi-Function Programs and Pointers


Objectives

  • Use function declarations (prototypes).
  • Code void functions.
  • Design a program using multiple functions as modules.
  • Develop functions as black boxes.
  • Add block comments to function declarations.



Grading Criteria (30pts + Extra Credit 2pts)

For each part: 10 pts: File Header 1pt, Function Headers 1pt, Compiles 2pts, Proper Formatting 1pt, Works as Specified 5pts
  1. funwork2.cpp (10pts)
  2. mealfun.cpp (10pts)
  3. blinkWithPointers.cpp (10pts)
  4. Extra Credit: xcmealfun.cpp (2pts)
Total Possible: 30 pts + Extra Credit 2pts

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.


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. Avoid duplicating code (see textbook page 208)
  2. Function naming conventions 
  3. Indentation in functions and placement of curly braces 
  4. No magic numbers. (Hint: make arrays of numbers const)
  5. Indentation in while statements and placement of curly braces
  6. No tab characters in your code.
  7. Meaningful variable names and consistent naming style (caps vs. underbars).

Project 1: Function Worksheet Sequel

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.

Project Specifications

  1. Start by downloading the worksheet: funwork2.cpp.      
    Functions

    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. You will see compiler warnings about "unused variables" until you fill in the functions.  When you finish this project,  there should be no more warnings.

  3. Add your name and the date to the file comment block at the top of the file where shown in the comments.
  4. No user input is required for this project and do not add any.
  5. Write the required functions as described by the function signature and comment block.

    Do NOT change any of the function signatures.

  6. Write the definitions for these functions below main(), and keep their prototypes above main().  
  7. Compile and run the code when finished with each function to verify correctness.

    Uncomment the function calls from main() as you progress. Do NOT change any code in main() beyond removing comments to run the code.

  8. When all of the tests pass, upload your completed funwork2.cpp file with the rest of the assignment.
Hints:
  • Remember that a warning is not a failure to compile but must be corrected before submitting the project.
  • For an example of printing the elements of an array, see lesson 8.1.4: Arrays as Function Parameters.



Image source

Project 2: Restaurant Math

Meals in a restaurant include the cost of purchasing the food, sales tax and tip (gratuity). Before the 20th century, Americans viewed tipping as inconsistent with the

Pizza
values of an egalitarian, democratic society. After prohibition, restaurants encouraged tipping to make up for losses due to the lack of alcohol sales and the opposition to tipping gradually faded. Tipping is now an American institution such that a 15% gratuity is now customary when a waiter provides adequate service at a restaurant with table service 

Project Specifications
  1. Write a program to help you calculate your bill at a restaurant.
  2. Name the source code file mealfun.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. Define between three and five functions besides the main() function. At least one function must be called from another function besides main().
  4. Define these functions below main(), and their declarations (prototypes) above main().
  5. Ask the user for the following inputs (and no other input) in this order and each on their own line, as shown in the Example Run below:
    1. Price of the meal
    2. Percent tip
  6. Assume the user may enter invalid data such as letters when numbers are wanted. Thus your program must detect and recover from invalid data entry, allowing the user to continue with the program after correcting the entry error.
  7. For the calculations, use a tax rate of 9.25%.
  8. Display the dollars and cents using two decimal places for the cents as shown in the Example Run. 
  9. 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 format of the output. Numbers must be on the same line as the tag explaining the number. For the input shown you must get the same numerical output. However, the output must change properly if the inputs are different.
    Welcome to the Restaurant Meal Calculator
    Enter the price of your meal: twenty-five dollars and 99 cents
    Error: enter numbers only!
    Enter the price of your meal: 25.99
    Enter the percent tip (10 min): fifteen
    Error: enter numbers only!
    Enter the percent tip (10 min): 5
    Must enter at least 10!
    Enter the percent tip (10 min): 15
    
    Food cost:   25.99
    Sales Tax:    2.40
    Gratuity:     3.90
    Total cost:  32.29
    Goodbye.
    
    Welcome to the Restaurant Meal Calculator
    Enter the price of your meal: 42.24
    Enter the percent tip (10 min): twelve
    Error: enter numbers only!
    Enter the percent tip (10 min): 2
    Must enter at least 10!
    Enter the percent tip (10 min): 12
    
    Food cost:   42.24
    Sales Tax:    3.91
    Gratuity:     5.07
    Total cost:  51.22
    Goodbye.
    

    In the above example runs, the user entered the values shown in aqua italics (for emphasis) to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics. The values in (parentheses) are expected values when entering the example input.

  10. After displaying the output, exit the program.
  11. Provide a block comment above each function prototype that describes the function using the format we discussed in class.
  12. Submit the source code file mealfun.cpp with the rest of the assignment.
Hints:
  • For examples of recovering from invalid input, see Key Sample Code (top of Schedule Page) or see lesson 5.3.7: Checking for cin Failure and 7.4.1: Grouping Repeated Commands.
References and More Information
  1. Segrave, Kerry (1998). Tipping: An American social history of gratuities. Jefferson, North Carolina: McFarland & Company. ISBN 0786403470 (Google preview).
  2. Gratuity - United States - History: Wikipedia, retrieved 2017-01-03.
  3. Publication 115, Tips, Gratuities, and Service Charges: California State Board of Equalization (tax administration)


Project 3:  Pointers

  1. Start with blink.cpp from HERE
  2. Save as blinkWithPointers.cpp
  3. Make sure it compiles as is.  Read through the code & run it.   You should see the output below.
  4. Other people want to use a blinkLights function,  so you’re going to create this function and reorganize your code to use it.
  5. Your new function name is blinkLights.  The purpose of blinkLights is to turn the lights to the state passed to it.  (Ex.  turn the lights ON means print “Light turned ON!”)
  6. Then blinkLights will change the state of its parameter variable.
  7. Here is the function header: 
/**
  blinkLights  - prints “Light turned ON!” or “Light turned OFF!” according to the parameter
  @param bool *whichState pointer to state you want to Write:
                                ON = 1 or OFF = 0
                 function switches state of the variable parameter before returning
  @return void
*/
  1. You will call blinkLights from main().  You want the same behavior as your original blink program as below.
  2. You must use a pointer in blinkLights and change the state OFF/ON inside blinkLights. 
  3. Turn blinkWithPointers in to Canvas with the rest of this Assignment. 


Extra Credit (2 pts)

The following is optional and worth extra credit points if the main program works well also:

  1. Create the correct spacing for the output of mealfun.cpp between the tag and the money using the setw() formatting manipulator described on pages 49-51 (1/e: 53-55) of the textbook. 

    To use this manipulator, include the iomanip library. For credit, save this as xcmealfun.cpp   Submit with the rest of this Assignment.


SOLUTION CODE:

funwork2.cpp

/**
    CS-11 Asn 8, funwork2.cpp
    Purpose: Practice writing functions.

    @author Sharon Strelitz
    @version 1.0 Date 12/28/2018
*/
#include <iostream>
using namespace std;

/**
    Given two temperatures, return true if one is less than 0
    and the other is greater than 100.
    @param temp1 First temperature to test.
    @param temp2 Second temperature to test.
    @return true if icy-hot; otherwise false.

    Test cases:
    icyHot(120, -1) ? true
    icyHot(-1, 120) ? true
    icyHot(2, 120) ? false
*/
bool icyHot(int temp1, int temp2);

/**
    Given a char, uses ASCII to determine if it is a number.
    @param num The character to test.
    @returns true if num is a number (0-9); otherwise returns false.

    Test cases:
    isNumber('a') ? false
    isNumber('3') ? true
*/
bool isNumber(char num);

/**
    Given a string, capitalizes all letters in the string using ASCII codes
    and if statements. Do NOT use toupper() or similar string functions.
    @param str The string to convert, which is returned by reference.

    Test cases:
    capitalizeString("I love cookies!") -> "I LOVE COOKIES!"
    capitalizeString("124 East Central Ave") -> "124 EAST CENTRAL AVE"
*/
void capitalizeString(string& str);

/**
    Given a string, converts any number in the string to a '+'.
    @param str The string to convert, which is returned by reference.

    Test cases:
    plusOut("123 East 9th St") -> "+++ East +th St"
    plusOut("Agent 007") -> "Agent +++"
    Hint: Use a for loop, and string indexing as in password project.
*/
void plusOut(string& str);

/**
    Prints the contents of an array with a for loop all on one line with a
    space between each number. Ends by printing a newline.
    @param data The array to print.
    @param size The number of elements in the array.
    @see lesson 8.1.4
*/
void printArray(const int data[], int size);

/**
    Given an array of ints, return true if the array is size 1 or more,
    AND the first element and the last element are equal.
    @param array An array of int numbers.
    @param size The number of elements in the array.

    Test cases:
    equalFirstLast([1, 2, 3], 3) ? false
    equalFirstLast([1, 2, 3, 1], 4) ? true
    equalFirstLast([1, 2, 1], 3) ? true
    equalFirstLast([3], 1) ? true
*/
bool equalFirstLast(int array[], int size);

/**
    Given an array of ints, multiplies each element in the array by itself.
    Remember that arrays are automatically pass by reference
    @param array An array of int numbers.
    @param size The number of elements in the array.

    Test cases:
    squareArray([1, 2, 3], 3) -> [1, 4, 9]
    squareArray([3, 5, 6, 8, 9], 5) -> [9, 25, 36, 64, 81]
    squareArray([3], 1) -> [9]
*/
void squareArray(int array[], int size);

int main()
{
    bool answer = false;
    string str;
    cout << boolalpha;

    cout << "***Testing icyHot***" << endl;
    answer = icyHot(120, -1); // uncomment after writing function
    cout << "icyHot1 should be true: " << answer << endl;
    answer = icyHot(-1, 120); // uncomment after writing function
    cout << "icyHot2 should be true: " << answer << endl;
    answer = icyHot(2, 120); // uncomment after writing function
    cout << "icyHot3 should be false: " << answer << endl;

    cout << "\n***Testing isNumber***"<< endl;
    answer = isNumber('a'); // uncomment after writing function
    cout << "isNumber1 should be false: " << answer << endl;
    answer = isNumber('9'); // uncomment after writing function
    cout << "isNumber2 should be true: " << answer << endl;

    cout << "\n***Testing capitalizeString***" << endl;
    str = "I love cookies!";
    capitalizeString(str); // uncomment after writing function
    cout << "capitalize1 should print I LOVE COOKIES!: " << str << endl;
    str = "124 East 9th St";
    capitalizeString(str); // uncomment after writing function
    cout << "capitalize2 should print 124 EAST 9TH ST: " << str << endl;

    cout << "\n***Testing plusOut***"<< endl;
    str = "123 East 9th Ave";
    plusOut(str); // uncomment after writing function
    cout << "plusOut1 should be +++ East +th Ave: " << str << endl;
    str = "Agent 007";
    plusOut(str); // uncomment after writing function
    cout << "plusOut2 should be Agent +++: " << str << endl;
    str = "Phone (123) 456-7890";
    plusOut(str); // uncomment after writing function
    cout << "plusOut3 should be Phone (+++) +++-++++: " << str << endl;

    cout << "\n***Testing printArray***" << endl;
    const int A3 = 3;
    int array1[] = {1, 2, A3};
    const int SIZE1 = 3;
    cout << "printArray1 should be 1 2 3: ";
    const int A10 = 10, A30 = 30, A50 = 50, A79 = 79;
    printArray(array1, SIZE1); // uncomment after writing function
    int array2[] = {A10, A30, A50, A79, A10};
    const int SIZE2 = 5;
    cout << "printArray2 should be 10 30 50 79 10: ";
    printArray(array2, SIZE2); // uncomment after writing function
    int array3[] = {A3};
    const int SIZE3 = 1;
    cout << "printArray3 should be 3: ";
    printArray(array3, SIZE3); // uncomment after writing function

    cout << "\n***Testing equalFirstLast***"<< endl;
    answer = equalFirstLast(array1, SIZE1); // uncomment after writing function
    cout << "equalFirstLast1 should be false: " << answer << endl;
    answer = equalFirstLast(array2, SIZE2); // uncomment after writing function
    cout << "equalFirstLast2 should be true: " << answer << endl;
    answer = equalFirstLast(array3, SIZE3); // uncomment after writing function
    cout << "equalFirstLast3 should be true: " << answer << endl;

    cout << "\n***Testing squareArray***" << endl;
    squareArray(array1, SIZE1); // uncomment after writing function
    cout << "squareArray1 should print 1 4 9: ";
    printArray(array1, SIZE1); // uncomment after writing function
    const int A5 = 5, A6 = 6, A8 = 8, A9 = 9;
    int array4[] = {A3, A5, A6, A8, A9};
    const int SIZE4 = 5;
    squareArray(array4, SIZE4); // uncomment after writing function
    cout << "squareArray2 should print 9 25 36 64 81: ";
    printArray(array4, SIZE4); // uncomment after writing function
    squareArray(array3, SIZE3); // uncomment after writing function
    cout << "squareArray3 should print 9: ";
    printArray(array3, SIZE3); // uncomment after writing function

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

    return 0;
}

bool icyHot(int temp1, int temp2){
    if (temp1 < 0 && temp2 > 100)  {
        return true;
    } else if (temp2 < 0 && temp1 > 100) {
            return true;
    } else {
        return false;
    }       
}

bool isNumber(char num)  {
    if (num > 47 && num < 58)  {
        return true;
    }  else  {
        return false;
    } 
}

void plusOut(string& str)  {
    for (int i = 0; i < (int) str.length(); i++)  {
        if (str[i] > 47 && str[i] < 58)  {
            str[i] = '+';
        }  
    }
}

void capitalizeString(string& str){
    for (int i = 0; i < (int) str.length(); i++) {
        if (str[i] > 96 && str[i] < 123)  {
            str[i] -= 32;
        }
    }
}

void printArray(const int data[], int size){
    for (int i = 0; i < size; i++)  {
        cout << data[i] << " "; 
    }
    cout << endl;
}

bool equalFirstLast(int array[], int size) {
    if (size <= 0 )  { //this is needed to avoid indexing off array bounds
        return false;
    }  else  if (array[0] == array[size - 1])  {
            return true;
    }  else {
            return false;
    }
}

void squareArray(int array[], int size)  {
    for (int i = 0; i < size; i++)  {
        array[i] *= array[i];
    }
}

mealfun.cpp
/**
    CS-11 Asn 8, mealfun.cpp
    Purpose: Calculate the tip at a restaurant.

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

/**
    getPrice:  get the meal price from user
               checking for invalid input

    @param  no input parameters
    @return returns the double price the user entered
*/
double getPrice();
/**
    getTipPercent:  get the tip percent from user
               tip percent must be >= 10

    @param  no input parameters
    @return returns the double tip the user entered
*/
double getTipPercent();
/**
    checkForNumeric:  check the user input for numeric input
             
    @param  no input parameters
    @return bool true = numeric
*/
bool checkForNumeric(double &input);

int main() {
    const double TAX = .0925;
    const double CONVERT_TIP = .01;
    double price = 0.0, tip = 0.0;
    cout << "Welcome to the Restaurant Meal Calculator" << endl;
    price = getPrice();
    //cout << "price is " << price << endl;
    tip = getTipPercent();
    //cout << "tip is " << tip << endl;
    tip *= CONVERT_TIP;
    //cout << "converted tip is " << tip << endl;
    cout << fixed << setprecision(2) << setw(8);
    double total = price + price * TAX + price * tip;
    cout << "Food cost: " << setw(7) << price << endl;
    cout << "Sales tax: "  <<  setw(7) << price * TAX << endl;
    cout << "Gratuity:  " << setw(7) << price * tip << endl;
    cout << "Total cost:" << setw(7) << total << endl;
    cout << "Goodbye." << endl;

    return 0;
}

double getPrice() {
    bool done = false;
    double userPrice = 0.0;
    while (!done)  {
        cout << "Enter the price of your meal: ";
        if (checkForNumeric(userPrice))  {
           done = true; 
           cin.clear();  //clear out anything left in input stream
           cin.ignore(1000, '\n');
        }
    }
    cin.clear();  //clear out anything left in input stream: error if user enters 2a
    //cin.ignore(1000, '\n');  //not needed here
    return userPrice;
}

double getTipPercent() {
    bool done = false;
    double userTip = 0.0;
    const int TIP_MINIMUM = 10;
    while (!done)  {
        cout << "Enter the percent tip (" << TIP_MINIMUM << "min): ";
        if (checkForNumeric(userTip)) {
            if ( userTip < TIP_MINIMUM)  {
                cout << "Must enter at least " << TIP_MINIMUM << "!" << endl;
                cin.clear();  //clear out anything left in input stream
                cin.ignore(1000, '\n');
            }  else  {
                done = true; 
            } 
        }            
    }
    cin.clear();  //clear out anything left in input stream
    cin.ignore(1000, '\n');
    return userTip;
}

bool checkForNumeric(double &input)  {
    cin >> input;
    if (cin.fail()) {  //user did not enter a numeric
                cout << "You must enter numbers, not characters\n";
                cin.clear();
                cin.ignore(1000, '\n');
                return false;
        }
    return true;
}

blinkWithPointers.cpp

/**
    CS-11 blink.cpp
    Purpose: blink a light on and off.

    @author Sharon Strelitz
    @version 1.0 2/07/18
*/
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
const bool ON = 1;
const bool OFF = 0;
const int MAX_BLINKS = 5;

/**
  blinkLight
  @param pointer to state you want to Write:  ON = 1 or OFF = 0
         function switches state of the variable pointed to
  @return void
*/
void blinkLight(bool *whichState)  {
  if (*whichState == ON)  {
      cout << "Light turned ON!" << endl;
  }  else  {
      cout << "Light turned OFF!" << endl;
  }
  *whichState = !*whichState;
}

int main() {
    bool state = ON;
    char response = 'y';
    cout << "do you want to turn the light off and on? (y/n) ";
    cin >> response;
    while ('y' == response)  {
       for (int i = 0; i < MAX_BLINKS; i++) {
          blinkLight(&state);
          std::this_thread::sleep_for(std::chrono::milliseconds(500));  //1000 ms is 1 second
          blinkLight(&state);
       }
       cout << "do you want to turn the light off and on? (y/n) ";
       cin >> response;
    }
}



Subpages (1): funwork2.cpp
Comments