Functions 1: Predefined and Value-Returning Functions

What are Functions?

In general, we use (call) functions (aka: modules, methods, procedures, subprocedures, or subprograms) to perform a specific (atomic) task. In algebra, a function is defined as a rule or correspondence between values, called the function's arguments, and the unique value of the function associated with the arguments. For example:

If f(x) = 2x + 5, then f(1) =  7, f(2) =  9, and f(3) = 11

1, 2, and 3 are arguments
7, 9, and 11 are the corresponding values
Bjarne Stroustrup's C++ Glossary

Predefined Functions

Using predefined functions:

C++ Standard Library reference
Rogue Wave C++ Standard Library Class Reference
Microsoft MSDN Library - Standard C++ Library Reference
Microsoft MSDN Library - C/C++ Languages

User-Defined Functions

Using User-Defined functions:

Function definition includes:
  1. Header (or heading) includes:
    1. Function name
    2. Number of parameters (if any)
    3. Data type of each parameter
    4. Type of function (data type or void)
  2. Body includes:
    1. Code to accomplish task
    2. ***Any variables (if any) declared in body of function are local to function
Function prototype includes: Function call includes:

Flow of Execution

Program Execution:

Function Example:
/*
This program illustrates value-returning functions 
  and compares two, then three numbers.
written by Mark K. Jowett, Ph.D.
6:03 PM 9/11/2004
*/

#include<iostream>
//using namespace std;

//function prototypes
double testTwo(double x, double y);
double testThree(double x, double y, double z);

int main() 
{
  double num1, num2;

  //value-returning function used in output
  std::cout << "The larger of 5 and 10 is "
	    << testTwo(5, 10) << std::endl; //function call

  std::cout << "Enter one number: ";
  std::cin >> num1;

  std::cout << "Enter another number: ";
  std::cin >> num2;
  std::cout << std::endl;

  //value-returning function used in output
  std::cout << "The larger of " << num1 << " and "
	    << num2 << " is " << testTwo(num1, num2) << std::endl; //function call

  //value-returning function used in output
  std::cout << "The largest of 10, 15, and 20 is "
	    << testThree(10, 15, 20) << std::endl; //function call

  std::cout << "Press Enter key to exit...";
  std::cin.get(); std::cin.get(); // make DOS window stay open

  return 0;
}

//function definition
double testTwo(double x, double y)
{
  if (x >= y)
    return x;
  else 
    return y;
}

//function definition
double testThree (double x, double y, double z)
{
//value-returning function used as argument in another function call
  return testTwo(x, testTwo(y, z));
}


Displays:
The larger of 5 and 10 is 10
Enter one number: 2
Enter another number: 3

The larger of 2 and 3 is 3
The largest of 10, 15, and 20 is 20
Press Enter key to exit...