0% found this document useful (0 votes)
12 views

Module 3 CSC 201

Uploaded by

peacewrld27
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Module 3 CSC 201

Uploaded by

peacewrld27
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

MODULE 3: Functions

Objectives
By the end of this module, you will
understand:
 Function main and other functions

 Passing parameters; by value and by

reference
 Variable Scope: local, global or static

 C++ rules for making functions

 Overloading functions
MODULE –4: Functions

 UNIT –4.1 Introduction


 UNIT –4.2 Functions in C++
 UNIT –4.3 Function having parameter(s)
 UNIT –4.4 Parameter Pass By Value
 UNIT –4.5 Parameter Pass By Reference
 UNIT –4.6 Scope of a variable
 UNIT –4.7 Math Functions
 UNIT –4.8 Function Overloading
4.1 Introduction

 The following program is to calculate the perimeter of a


rectangle based on the length and breadth input values
entered.
 //the following is a list of code statements written as a plain code in
function main
 #include <iostream>
 using namespace std;
 // function main
 int main()
 {
 double breadth, height, perimeter;
 cin >> breadth;
 cin >> height;
 perimeter = 2 * (breadth + height);
 Cout << “Perimeter of the rectangle = “ << perimeter <<endl;
 } //end of function main
 4.2 Functions in C++

 The code above to calculate perimeter


appear simple and cute. If a single program
has to do many self-contained independent
computations to bring about a solution to a
problem, then jamming together all the lines
of codes in one single main function might be
nightmares. Therefore, each independent
task that combines to bring about the final
solution to the problem might have to be
broken into code chunks and named as
functions.
 Functions

 A function is a complete section (block) of


C++ code with a definite start point and an
end point and its own set of variables.
 Functions should be designed so that they
have one primary task to accomplish.
 Functions can be passed data values and
they can return data.
 A function’s set of variables are only know by
the function and are called local variables –
i.e. they are local to that function.
 Functions

 Basic Things To Know:


 How to write a function within a program
 How to call a function within a program or
from another part of the program
 How to send information/data to a function
and how to get information back.
Advantage of function

 One solid advantage of creating a


function is that you can always re-use
it by just calling it instead of writing the
entire code again when it is needed
somewhere else within or outside the
immediate program.
 It is a good programming practice to

give a name that reflect what particular


task its doing.
A Function General format :

 function_return_type functionName([optional parameter


list separated by comma])
 {
 …set of codes to perform the function task…. //function body
 }

 A simple Example:
 void displayInfo()
 {
 cout << ”\nPls Enter Your Input Value\n”);
 cout << ”Note That Your Input is”;
 cout << ”within the range 0 – 24 :”;
 }
Explanation on the typical function
header

 The first line which declared the function is called


function header.
 Void:
 As used in the example above, when this function
terminates and does not send back or return any
information/ value but only display a message on
the screen, it means such does not return any
information/value. So we say the return type of the
function is void. But if has a value to send
somewhere else and such value is something like a
floating point value we can tag such function as of
type double instead of void.
Explanation on the typical function
header

 displayInfo():
 This is the name you chose to give the function,
followed by a pair of empty brackets, meaning the
function receives no value or parameter. Note, we can
send information or value into a function. This
information is or are some values a function will use to
perform its task. Also, the type of data(eg. int, double)
should also be stated.
 After declaration and definition, you get a function to
perform its task by calling the function. To call, use its
name followed by empty brackets when there is no
parameter to pass and a semicolon. e.g.
displayInfo();
Explanation on the typical function

 Function Declaration: Just like variable


declaration, a function must first be declared
before it can be used. A function declaration
takes the same form with the function header
ended with a semicolon. You can declare a
function as local or external just like you do
to a variable. This determines its scope.
 Note that the order of arrangement of
functions within a program/class has no effect
/ does not matter.
TUTOR MARKED ASSESSMENT (TMA)

Assignments/Tasks for the students:


1. Identify the error in the following function header:
Void double findAverage()

2. How do you call the following function


Void sumTotal()
{
-------
-------
-------
}

3. State the problem with the function declared with


printingOutput() and called with printingoutput()
4.3 Function having parameter(s)

 The following is the earlier program but now re-written into


two functions- the main and the calculatePerimeter.
 //program now written to use function
 #include <iostream>
 using namespace std;
 // function main
 int main()
 {
 double breadth, height, result;
 cin >> breadth;
 cin >> height;
 result = calculatePerimeter(breadth, height); //function is
called here,
 // send values of breath and height as
argument
 cout << “Perimeter of the rectangle = “ << result <<endl;
 } //end of function main
4.3 Function having parameter(s)

 double calculatePerimeter(double b, double h)


 //function header with parameters to receive argument
sent from function main
 {
 double Perimeter; // local variable used temporarily
within this method
 perimeter = 2 * (b + h);
 return perimeter; // value returned
 }// end of function calculatePerimeter
4.3 Function having parameter(s)

 The above function is named calculatePerimeter and it is


of type double(return type)
 The variables (b and h) declared as double within the
bracket are called parameters or formal parameters. They
hold the values of data sent in the order with which there
are arranged in the function parameter declaration
 Therefore, the main called calculatePerimeter with the
instruction “calculatePerimeter(breadth, height);” such that
breadth and height are the actual arguments sent to the
function.
 No code should be written after the word return else it
becomes unreachable.
 A void function needs no return statement, the function
simply terminates after the last statement.
4.4 Parameter Pass By Value:

 A function does not change the original value of variable


sent to it as a parameter because only a copy of the
variable is passed/ just a value.
 That is, a change in value of one of the parameters inside
the function / procedure is local to that function/procedure

 The following example is pass by value:

 calculatePerimeter(breadth, height);”
 calculatePerimeter(double b, double h)

By default, parameters in our functions are passed


by value.
4.5 Parameter Pass By Reference:

 Here, the formal parameters are bound to the reference values


of the actual parameters.
 A change in the value of a parameter inside the function
changes the value contained in the variable to which that
parameter refers.

 Pass by reference is well demonstrated using pointers. Pass


by reference also happens when an array is passed to a
function or when “&”(ampersand) operator is used in defining
a variable name.
 This is because the entire location/ address of the values are
passed and as such any change done by the receiving function
to the array changes the content of the array permanently
Pass By Reference Example:

 double calculateArea(double radius) //by value


 {
 return 3.14*pow(radius,2.0);
 }
 void calculateArea(double radius, double& area)// by
reference
 {
 area = 3.14*pow(radius,2.0);
 }
Pass By Reference Example:

 //operation in main; comparing pass by value to pass by


reference
 Int main()
 {
 double radius =5;
 double output;
 cout<<calculateArea(radius)<<endl;//for the pass by value
 calculateArea(radius, output); // for the pass by reference
 cout<<output<<endl; //output of the referenced
 }
Pros and cons : Reference

 Merit: Performance reasons, because it can


eliminate the pass-by-value overhead of copying
large amounts of data
 Demerit: Weaken security, because the called
function can corrupt the caller's data.
Second example: Array Pass by
reference
 void readT(double tmp[] );//function prototype
 int main()
 {
 double t [7]; // array t allocated initial memory space to contain 7
elements
 readT( t ); // t is passed to the function without any square bracket
 }

 //this function fills in the content of the array t; the change is permanent
 void readT(double tmp[] ) // note that tmp is a formal parameter receiving
from t
 {
 for (int i = 0; I < 7; ++i)
 {
 cout <<“Enter Temperature for day: ”<<( i+1) << endl;
 cin >> tmp[i];
 }
 }
 void readT(double tmp[] );//function prototype
 int main()
 {
 double t [ ] ;
 t = readT( );// this function fills the array and return it as object
 displayT(t);//this displays the content of the array pass
 }
 double [ ] readT( ) // [ ] after double means this is an array
 {
 double tmp [7];
 for (inti = 0; i<7; ++i)
 {
 cout<<“Enter Temperature for day: ”<<( i+1);
 cin>>tmp[i];
 }
 return tmp; //only the name is needed to return the array
 }

4.6 Scope of a variable:

 This is all about where a variable is declared - it is said to be visible


to that location. A variable declared within a particular function
cannot be used elsewhere. Except if declared outside all the
functions, it becomes external/global variable with larger scope and
can be accessed by all the functions within the program.
 int main()
 {
 int x = 1;
 myFunction(x);
 }
 variable y cannot be
 void myFunction(int xformal) used inside main and x
 { cannot be used inside
 int y; myFunction
 y = 20 *xformal;
 cout <<“value = ” << y <<endl;
 }
Scope of a variable:

 Generally, there are 3 categories, namely:


 Local
 Global
 Static

 Local Variables
The variables declared within the function body and in
the function header line input list belonging to that
function.
Visible and usable by the members of that function
Also called automatic variable
Fig.4.6: A program illustrating local and global variables.
Global Variables

 A global variable is declared outside any function


and is visible to all functions in that program file.
 All the functions can use and change a global variable.
 Global variables are declared above main().
 There is no need to pass them between functions.
 Global Variables are Hazardous
 Global variables should be used sparingly and with
considerable thought as well as subsequent
documentation – any function can inadvertently
manipulate the variable especially when not
desired(because all functions has access to it).
Static Variables

 Once a variable is declared static, the variable contents are


retained until the program is terminated.
 The variable is still visible only to the function and it is not
seen by any other parts of the program.
 The first time the function is entered, the static variable
initialization occurs.
 If there is no initial value assigned in the code, C++ initializes
the static variable to zero.
 The static variable initialization statement is performed only
once while the program is running.
 If a function must “remember” a value, even after the
program control has left that function, a static variable will
keep its value until the program ceases to run.
Static Variables

Here, only this function sees total. Every time it is called, it remembers the
value and keeps adding it to the previous total.
TUTOR MARKED ASSESSMENT (TMA)

Assignments/Tasks for the students:


1. Write a brief note on global, local and static variables and
write a code example of your own.
2. Consider the following code and state what happens if
variable y is referred to in another function without declaration
(still within the same program): Black Box
int main()
{
int y = 1;
myFunction(y);
}
3. What is the risk in unduly declaring a variable global
Benefits of Functions

 Reusability
 Information hiding
 Reducing complexity
Summarized rules for making a
function:

 The function name must follow standard C++


naming conventions.
 There may be one return type.
 If there is no return type, the void data type is used.
 The input argument list must have data type and
names (separated by commas if more than one, it
must correspond when calling i.e. in type and in
order)
 You may pass in as many arguments as you like
 If your list is empty (no arguments are
passed), the parentheses will be empty ()
Fig.4.9: A function returning a string value; also
need no parameter
4.7 Some Math Functions

 These are functions with predefined purposes available to


programmers to solve mathematical computations without
the need to reinvent the wheel.
 Function Description Example
 abs(x) Returns the absolute value of the argument abs(-2) is 2
 ceil(x) x is rounded up to its nearest integer and ceil(2.1) is 3
 returns this integer ceil(-2.1) is -2
 floor(x) x is rounded down to its nearest integer and floor(2.1) is 2
 returns this integer floor(-2.1) is -3
 exp(x) Returns the exponential function of x exp(1) is 2.71828
 pow(x, y) Returns a raised to power b (x y) pow(2.0, 3) is 8
 log(x) Returns the natural logarithm of x log(2.71828) is 1.0
 log10(x) Returns the base-10 logarithm of x log10(10.0) is 1
 sqrt(x) Returns the square root of x sqrt(4.0) is 2
4.8 Function Overloading

 Overloading is a feature in C++ when functions doing


different things uses the same name but different set of
parameter lists ( parameter types or their numbers in term of
quantity are different)

 When an overloaded function is called, the C++ compiler


selects the proper function by examining the number, types
and order of the arguments in the call.
 E.g.:
 int findMax(int a, int b);
 int findMax(int a, int b, int c);
 int findMax(int a, int b, int c, int d);
 double findMax(double a, doublt b);
4.8 Function Overloading

 int findMax(int a, int b)


 {
 if (a>b) return a;
 else return b;
 }
 int findMax(int a, int b, int c)
 {
 int biggest = a;
 if (b> biggest) biggest = b;
 if (c > biggest) biggest = c;
 return biggest;
 }
END OF MODULE ASSESSMENT (EMA)
Assignments/Tasks for the students:
1.Create a function to compute Xn such that the values of x and n are passed as
parameters to the function. [Hint]: The main function should send input arguments and
output the result from the function.
2.Create a function to implement the expression:

n is expected to be the input value passed to the function.

3. Write a program having five methods, such that one of the functions is the main where
others are called. Your main is to receive an input value n from the user and send to
other functions where necessary. Let the program implement the following:
a)Create a detectPrime function to test if the input received is prime or not
b)Create a detectOdd function to test is the input is odd number
c)Create a factorial function to compute the factorial value of the input
d)Create a summation function to compute 1 + 2 + 3 + … + n.
Note: Use a switch statement to select which function to call at a point in time

You might also like