Functions A function is a prepackaged block of

Functions • A function is a “pre-packaged” block of code – written to perform a well-defined task – Sometimes referred to as Procedures, Methods, or Subroutines • Functions are “called” by name – Information (variables) is “passed” to the function – Function executes and “returns” any results to the calling routine Professor John Carelli, Kutztown University Source: Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Example: sqrt Function (square root ) sqrt() function: • Accepts one number as an “input” • Returns one number as an “output” • i. e. the square root • Internally, the function contains code for computing the square root • Available in the cmath library • #include <cmath> Professor John Carelli, Kutztown University Example Usage: #include <cmath> … double x=16, y; y= sqrt(x); cout << y << endl; Output is: 4 2

Example: sqrt Function (square root ) • Function use in an assignment statement Function call Return value (output) y = sqrt(x); Function name Professor John Carelli, Kutztown University Function argument (input) Example Usage: #include <cmath> … double x=16, y; y= sqrt(x); cout << y << endl; Output is: 4 3 as Pearson Addison-Wesley Source: Pearson Education, Inc. Publishing

Function (in general) • Functions are called by name – As part of a statement • Information is “passed” to the function through “arguments” – Arguments are listed in parenthesis after the function name – Arguments can be variables or literals (fixed values) – There may be more than one argument (if so, they are comma separated) – Arguments are sometimes called “actual parameters” • Function executes internal code and “returns” a result – the “return value” effectively takes the place of the function in the statement Professor John Carelli, Kutztown University Function call: y= 1. 0 + sqrt(16); Effectively becomes: y= 1. 0 + 4. 0; Result: y is assigned a value of 5. 0

Library Functions • Goals of software engineering – reliable code – accomplished by code reuse • C++ promotes code reuse with predefined functions in the standard library – Included with C++ Professor John Carelli, Kutztown University 5 as Pearson Addison-Wesley Source: Pearson Education, Inc. Publishing

C++ cmath Library • Typical mathematical functions e. g. sqrt, sin, cos, log • Must include cmath library #include <cmath> Professor John Carelli, Kutztown University 6

Some Mathematical Library Functions Professor John Carelli, Kutztown University 7 as Pearson Addison-Wesley Source: Pearson Education, Inc. Publishing

Some Mathematical Library Functions (continued) Professor John Carelli, Kutztown University 8 as Pearson Addison-Wesley Source: Pearson Education, Inc. Publishing
- Slides: 8