Programming in C++ Language (0901 230) Lecture 5: Functions-Part1 Dr. Lubna Badri.
Post on 04-Jan-2016
218 Views
Preview:
Transcript
Programming in C++ LanguageProgramming in C++ Language(0901 230)(0901 230)
Lecture 5: Functions-Part1Dr. Lubna BadriDr. Lubna Badri
Lecture Overview
• Introduction to Functions– Dietel & Dietel: Chapter 3.– D.S. Malik: Chapters 6 and 7.
Functions: Divide and Conquer To write a program
Develop the algorithm that the program will use Translate the algorithm into the programming
language
Top Down Design (also called stepwise refinement) Break the algorithm into subtasks Break each subtask into smaller subtasks Eventually the smaller subtasks are trivial to
implement in the programming language
Introduction to Functions
• Divide and conquer technique– Construct a large program from small, simple
pieces (e.g., components)
• Functions – Facilitate the design, implementation,
operation and maintenance of large programs
• C++ Standard Library math functions
Benefits of top-down design• Subtasks, or functions in C++, make
programs– Easier to understand– Easier to change– Easier to write– Easier to test– Easier to debug– Easier for teams to develop
Program Components in C++• Programs written by
– combining new functions with “prepackaged” functions in the C++ standard library.
– The standard library provides a rich collection of functions.
• Functions are invoked by a function call – A function call specifies the function name and
provides information (as arguments) that the called function needs
– Boss to worker analogy: A boss (the calling function or caller) asks a worker
(the called function) to perform a task and return (i.e., report back) the results when the task is done.
Function Example
Function Components• Functions Declaration and Definition• Function Call• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local variables
• Parameters– Local variables passed when the function is called
that provide the function with outside information
Function Declaration• Tells the return type• Tells the name of the function• Tells how many arguments are needed• Tells the types of the arguments• Tells the formal parameter names
– Formal parameters are like placeholders for the actualarguments used when the function is called
– Formal parameter names can be any valid identifier
• Example:double total_cost(int number_par, double price_par);// Compute total cost including 5% sales tax on// number_par items at cost of price_par each
Function Definition• Provides the same information as the declaration • Describes how the function does its task
• Example:
double total_cost(int number_par, double price_par){ const double TAX_RATE = 0.05; //5% tax double subtotal; subtotal = price_par * number_par; return (subtotal + subtotal * TAX_RATE);}
function header
function body
Function Definitions• Create customized functions to
– Take in data– Perform operations– Return the result
• Format for function definition:return-value-type function-name( parameter-list )
{ declarations and statements}
• Example:int square( int y){ return y * y;}
Placing Definitions• A function call must be preceded by either
– The function’s declarationor
– The function’s definition• If the function’s definition precedes the call, a
declaration is not needed
• Placing the function declaration prior to the main function and the function definitionafter the main function leads naturally to building your own libraries in the future.
The Return Statement• Ends the function call• Returns the value calculated by the function• Syntax:
return expression;– expression performs the calculation
or– expression is a variable containing the
calculated value
• Example: return subtotal + subtotal * TAX_RATE;
Local Variables
• Variables declared in a function:– Are local to that function, they cannot be used
from outside the function– Have the function as their scope
• Variables declared in the main part of a program:– Are local to the main part of the program, they
cannot be used from outside the main part– Have the main part as their scope
3.5
Global Constants• Global Named Constant
– Available to more than one function as well as themain part of the program
– Declared outside any function body– Declared outside the main function body – Declared before any function that uses it
• Example: const double PI = 3.14159; double volume(double);
int main() {…}– PI is available to the main function and to function
volume
Global Variables• Global Variable -- rarely used when
more than one function must use a common variable– Declared just like a global constant except
const is not used.
– Generally make programs more difficult to understand and maintain.
Scope of Variables
1 // Fig. 6.13: fig06_13.cpp
2 // square function used to demonstrate the function
3
4 #include <iostream>
5 using std::cin;
6 using std::cout;
7 using std::endl;
8
9 int square( int ); // prototype for function square
10
11 int main()
12 {
13 int a = 10; // value to square (local automatic variable in main)
14
15 cout << a << " squared: " << square( a ) << endl; // display a squared
16 return 0; // indicate successful termination
17 } // end main
18
19 // returns the square of an integer
20 int square( int x ) // x is a local variable
21 {
22 return x * x; // calculate square and return result
23 } // end function square 10 squared: 100
Calling function square
Formal Parameters are Local Variables
• Formal Parameters are actually variables that are local to the function definition– They are used just as if they were declared in the
function body– Do NOT re-declare the formal parameters in the
function body, they are declared in the functiondeclaration
• The call-by-value mechanism– When a function is called the formal parameters
are initialized to the values of thearguments in the function call
Software Engineering Tip
• To promote software reusability, every function should be limited to performing a single, well-defined task, and the name of the function should express that task effectively. Such functions make programs easier to write, test, debug and maintain.
Error Prevention Tip
• A small function that performs one task is easier to test and debug than a larger function that performs many tasks.
Header Files• Header files
– Contain function prototypes for library functions– <cstdlib> , <cmath>, etc.– Load with #include <filename>
• Example:#include <cmath>
• Custom header files– Defined by the programmer– Save as filename.h– Loaded into program using
#include "filename.h"
Void Functions• Do not return a value.• May or may not have
formal parameters• Void functionName()
{
Statements
}
Predefined Functions C++ comes with libraries of predefined
functions
Example: sqrt function the_root = sqrt(9.0); returns, or computes, the square root
of a number The number, 9, is called the argument the_root will contain 3.0
3.2
Function Libraries • Predefined functions are found in libraries• The library must be “included” in a program
to make the functions available• An include directive tells the compiler which
library header file to include.• To include the math library containing sqrt():
#include <cmath>
Function Calls• sqrt(9.0) is a function call
– It invokes, or sets in action, the sqrt function– The argument (9), can also be a variable or an
expression
• A function call can be used like any expression– bonus = sqrt(sales) / 10;– Cout << “The side of a square with area “ << area
<< “ is “ << sqrt(area);
Math library functions.
Function Description Example
ceil( x ) rounds x to the smallest integer not less than x
ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x (x in radians)
cos( 0.0 ) is 1.0
exp( x ) exponential function ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer not greater than x
floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating-point number
fmod( 2.6, 1.2 ) is 0.2
log( x ) natural logarithm of x (base e)
log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128 pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x (x in radians)
sin( 0.0 ) is 0
sqrt( x ) square root of x (where x is a nonnegative value)
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x (x in radians)
tan( 0.0 ) is 0
Function Call Syntax
• Function_name (Argument_List)– Argument_List is a comma separated list:
(Argument_1, Argument_2, … , Argument_Last)
• Example:– side = sqrt(area);– cout << “2.5 to the power 3.0 is “
<< pow(2.5, 3.0);
top related