Here are a few questions to help you clarify your understanding of re-using functions.
Given the following function, name three (3) places you might use it in an application:
// Clears the Screen
//
// Input: none
// Output: none
//
// Action: makes the entire screen blank...
void clear_screen(void);
- just as we begin main
- before user input
- before results are displayed
- ...
Given the following function description, state three (3) different applications you might find for it (three situations where you might use it):
// Validate Ranged Input
//
// Input: prompt string, lower bound, upper bound
// Output: valid value entered from user
//
// Action: prints caller's prompt, reads user's entry,
// if their entry isn't in the specified range
// (inclusive), prints an error message and
// forces re-entry, otherwise returns valid
// entry
//
// Sample call:
//
// user_ent = range_input("This is your prompt: ", -4, 4);
- reading a score for a test having a known maximum number of points
- reading a die-roll total for a known set of dice
- reading the Arabic numeral for a Roman numeral conversion program
- reading the number of categories for a basket of flowers at the Busy Bee
Blossom Boutique
- ...
Given the following function description, find three (3) applications for it (three situations where you might use such a function):
// Find Char in String
//
// Input: string to search, character to find
// Output: position of character in string (-1 if not found)
//
// Action: searches through the string for the specified
// character; if not found, returns -1; if found
// indicates its position as an offset from the
// start of the string (the first position is 0 away
// from the start of the string)
//
// Sample call:
//
// offset = find("this is your string", ' ');
- determine the presence of a period in a string
- find the first occurrence of a hyphen in a string
- use in a loop and in conjunction with a replacement function to translate a string
into 13&+ speak
- ...
Given the following function, explain how you might use it in the given situations. (Actual code is preferred.)
// Sum Numbers
//
// Input: two numbers
// Output: sum of the numbers
//
// Action: adds its two numeric arguments and returns the sum
double sum(double x, double y);
add 3 numbers
sum( sum( a, b ), c )
average 2 numbers
sum( a, b ) / 2
subtract 2 numbers
sum( a, -b )
Given the following function, explain how you might use it in the given situations. (Actual code is preferred.)
// Average Numbers
//
// Input: two numbers
// Output: average of the numbers
//
// Action: adds its two numeric arguments and returns the sum
// divided by 2
double avg(double x, double y);
find a midpoint
(Hint: 2D, right?)
mid_x = avg( x1, x2 );
mid_y = avg( y1, y2 );
calculate the expected value of a dice roll
(Hint: Statistics are so weird!)
expect = avg( min_roll, max_roll );
sum 2 numbers
avg( a, b ) * 2