Chapter2 Function[1]
Chapter2 Function[1]
FUNCTIONS (Part 1)
Chapter’s Outcome
At the end of this chapter, student should be able to:
a) Learn how to build structured programs that are divided into
functions.
d) Learn how to use the library functions that are included with the
compiler.
e) List and explain the four basic types of statements. (This objective
is not from our textbook.)
Chapter’s Outline
1) Creating structured programs that are divided into functions
▪ When a program is very small, the entire program can reasonably be done as
part of main(). However, as your programs grow, it will be increasingly
more important to divide your program into subtasks, each of which can
be performed by an individual function.
2) Computations that are done more than once can be coded as functions.
This eliminates duplicating program instructions.
3) The process of dividing the program into smaller parts helps you to
determine the most appropriate algorithm for your problem. (This is called
top-down design.)
4) Modularizing (divided into smaller module) your program will make it much
easier to read, both for you and for everyone else.
Reasons to Use Functions (cont…)
5) Most importantly, separating individual tasks in functions makes your
program more robust and reusable. This is one of the major emphases of
object-oriented programming. The more independent and readable your
individual functions are, the easier it will be for you or someone else to
modify your code later, or to use it as part of a new program. This is the
strength of object-oriented design.
Predefined function
Predefined Functions (cont…)
▪ In order to use predefined function calls in your program, you need to
include the library containing the function you are interested in. For
example, to use sqrt and pow, you need to put the following statement near
the top of your file:
1) #include <math.h>
For example, sqrt(x); pow(x, y); abs(x); fabs(x); ceils(x);
floor(x);
2) #include <stdlib.h>
For example, labs(x); rand();
3) #include <string.h>
For example, strcmp(string1, string2); strcpy(var, string);
strlen(string);
4) #include <ctype.h>
For example, toupper(); tolower();
Predefined Functions
Predefined function are functions that have already been defined for you by C++. The
C++ language includes libraries of predefined functions that are available for use in
your programs. Some predefined function calls for #include <math.h> :
a) toupper();
change to uppercase
b) tolower();
change to lowercase
▪ If the functions are listed after the main function, then function prototypes
must be included at the top of the program, above the main function.
▪ The function prototypes "warn" the compiler about the eventual use of the
prototyped function and allocate memory.
▪ An error will definitely result if you call a function from within the main
function that has not been prototyped.
User Defined Functions (cont…)
Example of user defined function. User defined function will be used if the function is not
provided in the library.
User-defined Functions Structure
1) Function Definition
a) Function Name
b) Formal Parameter Lists
c) Return value
2) Function Prototype/Declaration
3) Function Call
Types of User-defined Functions
Three types of user-defined functions:
1) Function without return value and without parameter (void
function)
2) Function with return value but with parameter
3) Function without return value but with parameter
Function without return value & without parameter
(void function)
void DisplayMenu()
{
cout<<"---------------------------"<<endl;
cout<<" Choice | Operation "<<endl;
cout<<"---------------------------"<<endl;
cout<<" A | Addition "<<endl;
cout<<" B | Subtraction "<<endl;
cout<<"---------------------------"<<endl;
}
Function with return value & with parameter
sum = num1+num2;
return sum;
}
Function with return value & without parameter
float GetInput( )
{
float radius;
return radius;
}
CHAPTER 2
FUNCTIONS (Part 2)
Chapter’s Outline
1) Scope of variables – Global dan Local
4) List and explain the four basic types of statements. (This objective is not
from our textbook.)
User Defined Scope of Variables
int main()
{
int a = 10, b = 20; // Local variable declaration
g = a + b;
cout<<"G = "<<g<<endl;;
calTotal ();
return 0;
}
void calTotal ()
{
int total; // Local variable declaration
total = g * 2;
cout<<"Total = "<<total;
}
User Defined Local Variables
▪ A local variable is a variable declared within a block and not
accessible outside that block.
▪ Formal function parameters and variables declared within the body of a
function are local to that function:
void PrintLines( int numLines )
{
int count; // Loop control LOCAL VARIABLES
count = 1;
▪ This parameter list is a list of values that are passed to or from the function.
Sometimes, however, this parameter list is empty, because no values need to be
passed.
▪ When the parameter list is empty, the parentheses that are used to contain the
parameters are empty as shown in the example below.
▪ Example:
void main()
OR
int main()
▪ Most functions, though, contain at least one parameter in their parameter lists.
User Defined Parameters (cont…)
Why use parameters?
▪ Parameters that are "passed by value" provide information to the function that is
being called.
▪ When a parameter is passed by value, it does not change anything in the calling
function.
▪ (Parameters that change values in the calling function are called "pass by
reference" parameters; these will be discussed in a separate slide.)
Parameter passing in a function (cont…)
▪ When a function is "called" by the main function (or another function), one or more
arguments are passed to the function.
▪ On the receiving end, the function accepts these arguments (technically, as formal
parameters).
▪ The variable names of the arguments (that is, actual parameters) from the "calling"
function do not have to be the same as the names of the formal parameters in
the "called" function.
▪ But, the datatypes of the arguments and the parameters should match exactly. An
error could occur if the data types do not match.
Parameter passing in a function (cont…)
▪ We type "return 0;" as the last statement in the main functions of all
the programs that we write in this C++course.
1) by value,
2) by address,
3) by reference.
Parameter passing by value
PASSING BY VALUE is the preferred method. You simply use a variable name, an actual numeric literal, or an expression
in the parentheses of the call statement. This method is the safest because it does not actually change the value of the
argument in the calling function.
In the example below, the argument named price is passed by value to the function addTax.
#include <iostream.h>
double addTax(double);
int main()
{
double price = 10.00;
double finalPrice = 0.0;
//ACTUAL parameter
finalPrice = addTax(price); // function call
cout << "The final price with tax is " << finalPrice << endl;
return 0;
}// end of main
//FORMAL parameter
double addTax(double initialPrice)
{
return (initialPrice + initialPrice * 0.06);
}// end of addTax
Parameter passing by address
▪ Since arrays are actually pointers to one memory address, you are not passing the
actual array but just information that tells the function where the first element of the
array is stored in the RAM of the computer.
▪ Making changes to the array within the function will affect the values within the
array permanently, so this method should be used with care.
Parameter passing by reference
▪ PASSING BY REFERENCE is to be used when you want the function to actually and permanently
change the values of one or more variables. This method is dangerous but beneficial sometimes since
it allows you to affect the values of arguments in your calling function.
▪ You would purposefully pass by reference if you want to return 2 or more values to the calling function.
Since it is not possible in C++ to execute two return statements within a function and since it is not
possible to return two values in the same return statement (i.e. return myResult, myOtherResult
is illegal), passing by reference can allow you to modify two or more variables in the calling function (i.e.
main).
▪ Also, if you need to pass a really large variable or object, it saves memory to pass by reference. Since a
copy of the variable is not being made when you pass by reference, less memory overhead is required.
▪ For int, double, and char variables, passing by reference to save memory is not really necessary.
However, if you were to pass a large "object" such as a piece of clipart or a whole file, you would
intentionally pass by reference.
Reference(&) Parameter (cont…)
▪ You must use an ampersand (&) before the formal parameter names in the function header
(the first line of the function definition) to denote passing by reference.In the example
below, the argument named price is passed by reference to the function addTax.
#include <iostream.h>
int main()
{
double price = 10.00;