SlideShare una empresa de Scribd logo
1 de 34
CHAPTER 6

USER-DEFINED FUNCTIONS
           I
STANDARD (PREDEFINED) FUNCTIONS
• In college 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.
• If f(x) = 2x + 5, then                 f(1) = 7, f(2) = 9,
  and f(3) = 11
• 1, 2, and 3 are arguments, and 7, 9, and 11 are the corresponding
  values of the functions.



• Function in C++
   • Pre-defined (standard functions).
   • User-defined functions.
Pre-defined Functions
• Some of the pre-defined mathematical functions are abs(x),
  sqrt(x), and pow(x,y).
• The power function, pow(x,y), calculates xy; that is, the value of
  pow(x,y) = xy.
• pow(2,3) = 8.0 and pow(2.5,3) = 15.625.
• The function pow is of the type double or that the function pow
  returns a value of the type double.
• x and y are called the parameters (or arguments) of the function
  pow.
• Function pow has two parameters.
• The square root function, sqrt(x), calculates the non-negative
  square root of x for x >= 0.0.
• sqrt(2.25) is 1.5.
• The function sqrt is of the type double and has only one
  parameter.
• The floor function, floor, calculates the largest whole number that
  is not greater than x.
• floor(48.79) is 48.0.
• The function floor is of the type double and has only one
  parameter.
• In C++, pre-defined functions are organized into separate libraries.
• I/O functions are contained in the header file iostream.
• Math functions are contained in the header file cmath.
USER-DEFINED FUNCTIONS

User-defined functions in C++
   • Value-returning functions - functions that have a data type.
   • Void functions - functions that do not have a data type.
VALUE-RETURNING FUNCTIONS
• Some predefined C++ functions are: pow, islower, toupper.
• These are all examples of value-returning functions.
• To use these functions in our programs we must know the name of
  the header file containing the specification of the functions, include
  that header file in our program using the include statement and :
   1. The name of the function
   2. The number of parameters, if any
   3. The data type of each parameter
   4. Data type of the value computed (that is, the value returned) by
      the function, called the type of the function
• Since the value returned by a value-returning function is unique, the
  natural thing that we do with a value is:
   • Save the value for further calculation.
   • Use the value in some calculation.
   • Print the value.
• A value-returning function is either used in an assignment statement
  or in an output statement such as cout.
• In addition to the previous four properties, there is one more thing that
  is associated with a function:
   5. The code that is required to accomplish the task.
• The first four properties form, what is called the heading of the
  function
• The fifth property is called the body of the function.
• All together these five properties form, what is called the definition of
  the function.
• For predefined functions, we only need to be concerned with the first
  four properties not the fifth.
• For the function abs, the heading might look like

  int abs(int number)

• The function abs might have the following definition:
  int abs(int number)
  {
    if(number < 0)
       number = -number;
      return number;
  }

• The variable declared in the heading of the function abs is called
  the formal parameter of the function abs.
• The formal parameter of abs is number.
• Suppose that the heading of the function pow is

  double pow(double base, double exponent)

• The formal parameters of pow are base and exponent.


  double u = 2.5;
  double v = 3.0;
  double x, y, w;
  x = pow(u, v);                         //Line 1
  y = pow(2.0,3.2);                      //Line 2
  w = pow(u,7);                          //Line 3
• In Line 1, the function pow is called with the parameters u and v.
• The values of u and v are passed to the function pow.
• The value of u is copied into base and the value of v is copied into
  exponent.
• The variables u and v that appear in the call to the function pow in
  Line 1 are called actual parameters of that call.
• In Line 2, the function pow is called with parameters 2.0 and 3.2.
• The value 2.0 is copied into base and 3.2 is copied into
  exponent. In this call of the function pow, the actual parameters
  are 2.0 and 3.2, respectively.
• In Line 3, the actual parameters of the function pow are u and 7, the
  value of u is copied into base, and 7.0 is copied into exponent.
• Formal Parameter: A variable declared in the function
  heading.
• Actual Parameter: A variable or expression listed in a call
  to a function.
Syntax: Value-Returning Function

functionType functionName(formal parameter list)
{
    statements
}


• The functionType is the type of the value that is returned by the
  function.
• functionType is also called the data type of the value-returning
  function.
Syntax: Formal Parameter List
The syntax of the formal parameter list is:
  dataType identifier, dataType identifier, ...
Function Call: Syntax
functionName(actual parameter list)


Syntax: Actual Parameter List
expression or variable,expression or variable, ...
• A function’s formal parameter list can be empty.
• If the formal parameter list is empty, the parentheses are still needed.
• The function heading of the value-returning function takes, if the
  parameter list is empty, either of the following forms:

  functionType functionName()
  or
  functionType functionName(void)
• If the formal parameter list is empty, in a function call the actual
  parameter is also empty.
• A call to a value-returning function with an empty formal parameter
  list is

  functionName()
The return Statement
• Once the function computes the value, the function returns this value
  via the return statement.

Syntax: return Statement
The syntax of the return statement is:

 return expression or variable;

• In C++, return is a reserved word.

• When a return statement executes in a function, the function
  immediately terminates and the control goes back to the caller.
• When a return statement executes in the function main, the
  program terminates.
Function to return the larger of two numbers.

double larger(double x, double y)
{
   double max;

    if(x >= y)
       max = x;
    else
       max = y;
    return max;
}
double larger(double x, double y)
{
  if(x >= y)
     return x;
  else
     return y;
}

• The first form of the function larger requires that you use an
  additional variable max (called a local declaration, where max is a
  variable local to the function larger); the second form does not.
• x and y are formal parameters.
int main()
{
   double one, two, maxNum;                  //Line 1

    cout<<"Larger of 5 and 6 is "
       <<larger(5,6)<<endl;                  //Line   2
    cout<<"Enter two numbers: ";             //Line   3
    cin>>one>>two;                           //Line   4
    cout<<endl;                              //Line   5
    cout<<"Larger of "<<one<<" and "<<two
        <<" is "<<larger(one,two)<<endl;     //Line 6
    cout<<"Larger of "<<one<<" and 29 is "
       <<larger(one,29)<<endl;               //Line 7
    maxNum = larger(38.45, 56.78);           //Line 8
    cout<<"maxNum = "<<maxNum<<endl;         //Line 9

    return 0;
}
1. The expression larger(5,6), at Line 2, is a function call, and 5
   and 6 are actual parameters.
2. The expression larger(one, two), at Line 6, is a function call.
   Here, one and two are actual parameters.
3. The expression larger(one, 29), at Line 7, is also a function
   call. Here, one and 29 are actual parameters.
4. The expression larger(38.45, 56.78); at Line 8 is a function
   call. In this call, the actual parameters are 38.45 and 56.78. In this
   statement, the value returned by the function larger is assigned to
   the variable maxNum.
• Once a function is written it can be used anywhere in the program.


• Let us write another function that uses the function larger to
  determine the larger of three numbers. We call this function
  compareThree.

double compareThree(double x, double y, double z)
{
   return larger(x,larger(y,z));
}
Function Prototype
• Function Prototype: Function heading without the body of the
  function is called a function prototype.

Syntax: Function Prototype
functionType functionName(parameter list);

• Note the semicolon at the end.


Example:
For the function larger, the function prototype is:

     double larger(double x, double y);
• When writing the function prototype, it is not necessary to specify
  the variable name in the parameter list. However, the data type of
  each parameter must be specified.

• We can rewrite the function prototype of the function larger as
  follows:
 double larger(double, double);
Example
//Program: Largest of three numbers
#include <iostream>
using namespace std;

double larger(double x, double y);
double compareThree(double x, double y, double z);

int main()
{
   double one, two;                       //Line 1

   cout<<"Line 2: Larger of 5 and 10 is "
       <<larger(5,10)<<endl;              //Line 2
   cout<<"Line 3: Enter two numbers: ";   //Line 3
   cin>>one>>two;                         //Line 4
   cout<<endl;                            //Line 5
cout<<"Line 6: Larger of "<<one<<" and "
        <<two<<" is "<<larger(one,two)<<endl;//Line 6
    cout<<"Line 7: Largest of 23, 34, and 12 is "
        <<compareThree(23,34,12)<<endl;    //Line 7
    return 0;
}
double larger(double x, double y)
{
   if(x >= y)
      return x;
   else
      return y;
}
double compareThree (double x, double y, double z)
{
   return larger(x,larger(y,z));
}
Sample Run: The user input is in red.
Line 2: Larger of 5 and 10 is 10
Line 3: Enter two numbers: 25 73
Line 6: Larger of 25 and 73 is 73
Line 7: Largest of 23, 34, and 12 is 34



• Since we have included function prototypes in our program, function
  larger and compareThree can appear in any order.
• Recall that in a value-returning function the return statement
  returns the value.
• Consider the following return statement:

return x, y;          // only the value y will be returned

• This is a legal return statement.
• You might think that this return statement is returning the values of
  x and y.
• This is not the case.
• A return statement returns only one value, even if the return
  statement contains more than one expression.
• If a return statement contains more than one expression, only the
  value of the last expression is returned.
• Therefore, in the case of the above return statement, the value of y
  is returned.
Flow of Execution
• When the program is executed (that is, run) execution always begins
  at the first statement in the function main no matter where it is
  placed in the program.
• Other functions are executed only when they are called.
• Function prototypes appear before any function definition, so the
  compiler translates these first. The compiler can then correctly
  translate a function call.
• A function call statement results in the transfer of control to the first
  statement in the body of the called function.
• After the last statement of the called function is executed, the
  control is passed back to the point immediately following the
  function call.
• A value-returning function returns a value. Therefore, for value-
  returning functions, after executing the function when the control
  goes back to the caller, the value that the function returns replaces
  the function call statement.
PROGRAMMING EXAMPLE: LARGEST NUMBER

In this programming example, the function larger is used to
determine the largest number from a set of numbers. For the purpose of
illustration, this program determines the largest number from a set of
10 numbers.

Input: A set of 10 numbers.

Output: The largest of 10 numbers.
Problem Analysis and Algorithm Design
Suppose that the input data is:
15 20 7 8 28 21 43 12 35 3
• Read the first number of the data set.
• Since this is the only number read to this point, you may assume that
  it is the largest number so far and call it max.
• Read the second number and call it num.
• Now compare max and num, and store the larger number into max.
• Now max contains the larger of the first two numbers.
• Read the third number. Compare it with max and store the larger
  number into max.
• At this point, max contains the largest of the first three numbers.
  Read the next number, compare it with max, and store the larger into
  max.
• Repeat this process for each remaining number in the data set.
1. Read the first number. Since this is the only number that you have
  read so far, it is the largest number so far. Save it in a variable called
  max.
2. For each remaining number in the list,
    a. Read the next number. Store it in a variable called num.
    b. Compare num and max. If max < num, then num is the new
       largest number and so update the value of max by copying num
       into max. If max >= num, discard num; that is, do nothing.
3. Because max now contains the largest number, print it.



To find the larger of two numbers we use the function larger.
// Program: Largest
#include <iostream>
using namespace std;
double larger(double x, double y);
int main()
{ double num; //variable to hold the current number
   double max; // variable to hold the larger number
   int count; // loop control variable
  cout<<"Enter 10 numbers."<<endl;
  cin>>num;                                //Step 1

  max = num;                               //Step 1

  for(count = 1; count < 10; count++)      //Step 2
  {
    cin>>num;                              //Step 2a
    max = larger(max, num);                //Step 2b
  }
cout<<"The largest number is "<<max<<endl;
                                           //Step 3
   return 0;
}//end main

double larger(double x, double y)
{
   if(x >= y)
    return x;
   else
    return y;
}
Sample Run: In this sample run, the user input is in red
Enter 10 numbers.
10 56 73 42 22 67 88 26 62 11
The largest number is 88

Más contenido relacionado

La actualidad más candente (20)

03 function overloading
03 function overloading03 function overloading
03 function overloading
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
 
Call by value
Call by valueCall by value
Call by value
 
Functions
FunctionsFunctions
Functions
 
Working with functions in matlab
Working with functions in matlabWorking with functions in matlab
Working with functions in matlab
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Function in c++
Function in c++Function in c++
Function in c++
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversion
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 

Destacado

Concept stores for kids are a growing market in UK - CORNU Estelle
Concept stores for kids are a growing market in UK - CORNU EstelleConcept stores for kids are a growing market in UK - CORNU Estelle
Concept stores for kids are a growing market in UK - CORNU EstelleEstelle Cornu
 
Store in Store Marketing
Store in Store MarketingStore in Store Marketing
Store in Store Marketingkarmasaca
 
Case Store21
Case Store21Case Store21
Case Store21dsnith
 
Collective concept store presentation
Collective concept store presentationCollective concept store presentation
Collective concept store presentationAndrij Prjazevskyj
 
Beautiful Convergence: Exploring the changing face of beauty retail
Beautiful Convergence: Exploring the changing face of beauty retailBeautiful Convergence: Exploring the changing face of beauty retail
Beautiful Convergence: Exploring the changing face of beauty retailDalziel and Pow
 
14 12-2011 - arezzo&co investor day - apresentação varejo
14 12-2011 - arezzo&co investor day - apresentação varejo14 12-2011 - arezzo&co investor day - apresentação varejo
14 12-2011 - arezzo&co investor day - apresentação varejoArezzori
 
Chanel Experiential Concept Store
Chanel Experiential Concept StoreChanel Experiential Concept Store
Chanel Experiential Concept StoreDenis Stephan
 
Millennials 4.0 - Faith & Religion
Millennials 4.0 - Faith & ReligionMillennials 4.0 - Faith & Religion
Millennials 4.0 - Faith & ReligionBuzz Marketing Group
 
Group Project Proposal for Multi-label Concept Store, Contempo. 2011.
Group Project Proposal for Multi-label Concept Store, Contempo. 2011.Group Project Proposal for Multi-label Concept Store, Contempo. 2011.
Group Project Proposal for Multi-label Concept Store, Contempo. 2011.Ena Teo Jia En
 
Using Comics In The Design Process Upa Boston Cueva
Using Comics In The Design Process Upa Boston CuevaUsing Comics In The Design Process Upa Boston Cueva
Using Comics In The Design Process Upa Boston CuevaAmy Cueva
 
A report of opening a new book shop.
A report of opening a new book shop.A report of opening a new book shop.
A report of opening a new book shop.Choco Lash
 
Retail Marketing Project : Store conceptualization
Retail Marketing Project : Store conceptualizationRetail Marketing Project : Store conceptualization
Retail Marketing Project : Store conceptualizationSuhasini Jain
 
Virtual stores the future of retail
Virtual stores the future of retailVirtual stores the future of retail
Virtual stores the future of retailBharat Bharadwaj
 

Destacado (20)

New Materialities
New MaterialitiesNew Materialities
New Materialities
 
Emanuel Gomes Monteiro
Emanuel Gomes MonteiroEmanuel Gomes Monteiro
Emanuel Gomes Monteiro
 
Concept stores for kids are a growing market in UK - CORNU Estelle
Concept stores for kids are a growing market in UK - CORNU EstelleConcept stores for kids are a growing market in UK - CORNU Estelle
Concept stores for kids are a growing market in UK - CORNU Estelle
 
Store in Store Marketing
Store in Store MarketingStore in Store Marketing
Store in Store Marketing
 
Case Store21
Case Store21Case Store21
Case Store21
 
Collective concept store presentation
Collective concept store presentationCollective concept store presentation
Collective concept store presentation
 
Beautiful Convergence: Exploring the changing face of beauty retail
Beautiful Convergence: Exploring the changing face of beauty retailBeautiful Convergence: Exploring the changing face of beauty retail
Beautiful Convergence: Exploring the changing face of beauty retail
 
Apresentação vimer 2011 ev
Apresentação vimer 2011 evApresentação vimer 2011 ev
Apresentação vimer 2011 ev
 
14 12-2011 - arezzo&co investor day - apresentação varejo
14 12-2011 - arezzo&co investor day - apresentação varejo14 12-2011 - arezzo&co investor day - apresentação varejo
14 12-2011 - arezzo&co investor day - apresentação varejo
 
Chanel Experiential Concept Store
Chanel Experiential Concept StoreChanel Experiential Concept Store
Chanel Experiential Concept Store
 
Millennials 4.0 - Faith & Religion
Millennials 4.0 - Faith & ReligionMillennials 4.0 - Faith & Religion
Millennials 4.0 - Faith & Religion
 
Samsung
SamsungSamsung
Samsung
 
Shopper's Stop retail
Shopper's Stop retail Shopper's Stop retail
Shopper's Stop retail
 
Group Project Proposal for Multi-label Concept Store, Contempo. 2011.
Group Project Proposal for Multi-label Concept Store, Contempo. 2011.Group Project Proposal for Multi-label Concept Store, Contempo. 2011.
Group Project Proposal for Multi-label Concept Store, Contempo. 2011.
 
Using Comics In The Design Process Upa Boston Cueva
Using Comics In The Design Process Upa Boston CuevaUsing Comics In The Design Process Upa Boston Cueva
Using Comics In The Design Process Upa Boston Cueva
 
A report of opening a new book shop.
A report of opening a new book shop.A report of opening a new book shop.
A report of opening a new book shop.
 
Retail Marketing Project : Store conceptualization
Retail Marketing Project : Store conceptualizationRetail Marketing Project : Store conceptualization
Retail Marketing Project : Store conceptualization
 
Online store presentation
Online store presentationOnline store presentation
Online store presentation
 
Winning in Design
Winning in DesignWinning in Design
Winning in Design
 
Virtual stores the future of retail
Virtual stores the future of retailVirtual stores the future of retail
Virtual stores the future of retail
 

Similar a 06

User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in CRAJ KUMAR
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxGebruGetachew2
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college2017eee0459
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and commentMalligaarjunanN
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)Arpit Meena
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4Saranya saran
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptxAshwini Raut
 

Similar a 06 (20)

Functions
FunctionsFunctions
Functions
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in C
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Pro
ProPro
Pro
 
Function
Function Function
Function
 

06

  • 2. STANDARD (PREDEFINED) FUNCTIONS • In college 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. • If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11 • 1, 2, and 3 are arguments, and 7, 9, and 11 are the corresponding values of the functions. • Function in C++ • Pre-defined (standard functions). • User-defined functions.
  • 3. Pre-defined Functions • Some of the pre-defined mathematical functions are abs(x), sqrt(x), and pow(x,y). • The power function, pow(x,y), calculates xy; that is, the value of pow(x,y) = xy. • pow(2,3) = 8.0 and pow(2.5,3) = 15.625. • The function pow is of the type double or that the function pow returns a value of the type double. • x and y are called the parameters (or arguments) of the function pow. • Function pow has two parameters.
  • 4. • The square root function, sqrt(x), calculates the non-negative square root of x for x >= 0.0. • sqrt(2.25) is 1.5. • The function sqrt is of the type double and has only one parameter. • The floor function, floor, calculates the largest whole number that is not greater than x. • floor(48.79) is 48.0. • The function floor is of the type double and has only one parameter. • In C++, pre-defined functions are organized into separate libraries. • I/O functions are contained in the header file iostream. • Math functions are contained in the header file cmath.
  • 5.
  • 6. USER-DEFINED FUNCTIONS User-defined functions in C++ • Value-returning functions - functions that have a data type. • Void functions - functions that do not have a data type.
  • 7. VALUE-RETURNING FUNCTIONS • Some predefined C++ functions are: pow, islower, toupper. • These are all examples of value-returning functions. • To use these functions in our programs we must know the name of the header file containing the specification of the functions, include that header file in our program using the include statement and : 1. The name of the function 2. The number of parameters, if any 3. The data type of each parameter 4. Data type of the value computed (that is, the value returned) by the function, called the type of the function
  • 8. • Since the value returned by a value-returning function is unique, the natural thing that we do with a value is: • Save the value for further calculation. • Use the value in some calculation. • Print the value. • A value-returning function is either used in an assignment statement or in an output statement such as cout. • In addition to the previous four properties, there is one more thing that is associated with a function: 5. The code that is required to accomplish the task. • The first four properties form, what is called the heading of the function • The fifth property is called the body of the function. • All together these five properties form, what is called the definition of the function. • For predefined functions, we only need to be concerned with the first four properties not the fifth.
  • 9. • For the function abs, the heading might look like int abs(int number) • The function abs might have the following definition: int abs(int number) { if(number < 0) number = -number; return number; } • The variable declared in the heading of the function abs is called the formal parameter of the function abs. • The formal parameter of abs is number.
  • 10. • Suppose that the heading of the function pow is double pow(double base, double exponent) • The formal parameters of pow are base and exponent. double u = 2.5; double v = 3.0; double x, y, w; x = pow(u, v); //Line 1 y = pow(2.0,3.2); //Line 2 w = pow(u,7); //Line 3
  • 11. • In Line 1, the function pow is called with the parameters u and v. • The values of u and v are passed to the function pow. • The value of u is copied into base and the value of v is copied into exponent. • The variables u and v that appear in the call to the function pow in Line 1 are called actual parameters of that call. • In Line 2, the function pow is called with parameters 2.0 and 3.2. • The value 2.0 is copied into base and 3.2 is copied into exponent. In this call of the function pow, the actual parameters are 2.0 and 3.2, respectively. • In Line 3, the actual parameters of the function pow are u and 7, the value of u is copied into base, and 7.0 is copied into exponent.
  • 12. • Formal Parameter: A variable declared in the function heading. • Actual Parameter: A variable or expression listed in a call to a function.
  • 13. Syntax: Value-Returning Function functionType functionName(formal parameter list) { statements } • The functionType is the type of the value that is returned by the function. • functionType is also called the data type of the value-returning function.
  • 14. Syntax: Formal Parameter List The syntax of the formal parameter list is: dataType identifier, dataType identifier, ...
  • 15. Function Call: Syntax functionName(actual parameter list) Syntax: Actual Parameter List expression or variable,expression or variable, ...
  • 16. • A function’s formal parameter list can be empty. • If the formal parameter list is empty, the parentheses are still needed. • The function heading of the value-returning function takes, if the parameter list is empty, either of the following forms: functionType functionName() or functionType functionName(void) • If the formal parameter list is empty, in a function call the actual parameter is also empty. • A call to a value-returning function with an empty formal parameter list is functionName()
  • 17. The return Statement • Once the function computes the value, the function returns this value via the return statement. Syntax: return Statement The syntax of the return statement is: return expression or variable; • In C++, return is a reserved word. • When a return statement executes in a function, the function immediately terminates and the control goes back to the caller. • When a return statement executes in the function main, the program terminates.
  • 18. Function to return the larger of two numbers. double larger(double x, double y) { double max; if(x >= y) max = x; else max = y; return max; }
  • 19. double larger(double x, double y) { if(x >= y) return x; else return y; } • The first form of the function larger requires that you use an additional variable max (called a local declaration, where max is a variable local to the function larger); the second form does not. • x and y are formal parameters.
  • 20. int main() { double one, two, maxNum; //Line 1 cout<<"Larger of 5 and 6 is " <<larger(5,6)<<endl; //Line 2 cout<<"Enter two numbers: "; //Line 3 cin>>one>>two; //Line 4 cout<<endl; //Line 5 cout<<"Larger of "<<one<<" and "<<two <<" is "<<larger(one,two)<<endl; //Line 6 cout<<"Larger of "<<one<<" and 29 is " <<larger(one,29)<<endl; //Line 7 maxNum = larger(38.45, 56.78); //Line 8 cout<<"maxNum = "<<maxNum<<endl; //Line 9 return 0; }
  • 21. 1. The expression larger(5,6), at Line 2, is a function call, and 5 and 6 are actual parameters. 2. The expression larger(one, two), at Line 6, is a function call. Here, one and two are actual parameters. 3. The expression larger(one, 29), at Line 7, is also a function call. Here, one and 29 are actual parameters. 4. The expression larger(38.45, 56.78); at Line 8 is a function call. In this call, the actual parameters are 38.45 and 56.78. In this statement, the value returned by the function larger is assigned to the variable maxNum.
  • 22. • Once a function is written it can be used anywhere in the program. • Let us write another function that uses the function larger to determine the larger of three numbers. We call this function compareThree. double compareThree(double x, double y, double z) { return larger(x,larger(y,z)); }
  • 23. Function Prototype • Function Prototype: Function heading without the body of the function is called a function prototype. Syntax: Function Prototype functionType functionName(parameter list); • Note the semicolon at the end. Example: For the function larger, the function prototype is: double larger(double x, double y);
  • 24. • When writing the function prototype, it is not necessary to specify the variable name in the parameter list. However, the data type of each parameter must be specified. • We can rewrite the function prototype of the function larger as follows: double larger(double, double);
  • 25. Example //Program: Largest of three numbers #include <iostream> using namespace std; double larger(double x, double y); double compareThree(double x, double y, double z); int main() { double one, two; //Line 1 cout<<"Line 2: Larger of 5 and 10 is " <<larger(5,10)<<endl; //Line 2 cout<<"Line 3: Enter two numbers: "; //Line 3 cin>>one>>two; //Line 4 cout<<endl; //Line 5
  • 26. cout<<"Line 6: Larger of "<<one<<" and " <<two<<" is "<<larger(one,two)<<endl;//Line 6 cout<<"Line 7: Largest of 23, 34, and 12 is " <<compareThree(23,34,12)<<endl; //Line 7 return 0; } double larger(double x, double y) { if(x >= y) return x; else return y; } double compareThree (double x, double y, double z) { return larger(x,larger(y,z)); }
  • 27. Sample Run: The user input is in red. Line 2: Larger of 5 and 10 is 10 Line 3: Enter two numbers: 25 73 Line 6: Larger of 25 and 73 is 73 Line 7: Largest of 23, 34, and 12 is 34 • Since we have included function prototypes in our program, function larger and compareThree can appear in any order.
  • 28. • Recall that in a value-returning function the return statement returns the value. • Consider the following return statement: return x, y; // only the value y will be returned • This is a legal return statement. • You might think that this return statement is returning the values of x and y. • This is not the case. • A return statement returns only one value, even if the return statement contains more than one expression. • If a return statement contains more than one expression, only the value of the last expression is returned. • Therefore, in the case of the above return statement, the value of y is returned.
  • 29. Flow of Execution • When the program is executed (that is, run) execution always begins at the first statement in the function main no matter where it is placed in the program. • Other functions are executed only when they are called. • Function prototypes appear before any function definition, so the compiler translates these first. The compiler can then correctly translate a function call. • A function call statement results in the transfer of control to the first statement in the body of the called function. • After the last statement of the called function is executed, the control is passed back to the point immediately following the function call. • A value-returning function returns a value. Therefore, for value- returning functions, after executing the function when the control goes back to the caller, the value that the function returns replaces the function call statement.
  • 30. PROGRAMMING EXAMPLE: LARGEST NUMBER In this programming example, the function larger is used to determine the largest number from a set of numbers. For the purpose of illustration, this program determines the largest number from a set of 10 numbers. Input: A set of 10 numbers. Output: The largest of 10 numbers.
  • 31. Problem Analysis and Algorithm Design Suppose that the input data is: 15 20 7 8 28 21 43 12 35 3 • Read the first number of the data set. • Since this is the only number read to this point, you may assume that it is the largest number so far and call it max. • Read the second number and call it num. • Now compare max and num, and store the larger number into max. • Now max contains the larger of the first two numbers. • Read the third number. Compare it with max and store the larger number into max. • At this point, max contains the largest of the first three numbers. Read the next number, compare it with max, and store the larger into max. • Repeat this process for each remaining number in the data set.
  • 32. 1. Read the first number. Since this is the only number that you have read so far, it is the largest number so far. Save it in a variable called max. 2. For each remaining number in the list, a. Read the next number. Store it in a variable called num. b. Compare num and max. If max < num, then num is the new largest number and so update the value of max by copying num into max. If max >= num, discard num; that is, do nothing. 3. Because max now contains the largest number, print it. To find the larger of two numbers we use the function larger.
  • 33. // Program: Largest #include <iostream> using namespace std; double larger(double x, double y); int main() { double num; //variable to hold the current number double max; // variable to hold the larger number int count; // loop control variable cout<<"Enter 10 numbers."<<endl; cin>>num; //Step 1 max = num; //Step 1 for(count = 1; count < 10; count++) //Step 2 { cin>>num; //Step 2a max = larger(max, num); //Step 2b }
  • 34. cout<<"The largest number is "<<max<<endl; //Step 3 return 0; }//end main double larger(double x, double y) { if(x >= y) return x; else return y; } Sample Run: In this sample run, the user input is in red Enter 10 numbers. 10 56 73 42 22 67 88 26 62 11 The largest number is 88