Chapter 3 Function
Chapter 3 Function
Fundamental of Programming II
Jimma, Ethiopia.
Objective of this chapter:
What is function.
Types of C++ functions:
Standard functions
User-defined functions
Declaring and Implementing C++ functions
Calling functions with arguments and return a value from a function.
Difference between global and local variable
Function parameter and default function parameter
Overloading function
Recursive function
Inline function
Passing array to function
2
Introducation
The Top-down design approach is based on dividing the main problem into
smaller tasks which may be divided into simpler tasks, then implementing each
simple task by a subprogram or a function.
Used for effective development and maintenance of large programs and projects.
For large programs it is not practical to put the entire programming instructions
into one function.
3
Cont..
A natural way to solve large problems is to break them down into a series
of sub-problems, which can be solved more-or-less independently and then
combined to arrive at a complete solution.
4
Cont..
Functions are like building blocks. They let you divide complicated
programs into manageable pieces.
While working on one function, you can focus on just that part of the
program and construct it, debug it, and perfect it.
5
Function
It is a group of statements that together perform a task on data and returns a
value.
At least one function in C++ program which is main() which is called
automatically when the program is starts.
Each function has its own name, and when that name is called(invoked), the
execution of the program branches to the body of that function. When the
function returns, execution resumes on the next line of the calling function
6
Cont…
C++ language is shipped with a lot of functions which are known as standard
functions. It is part of compiler package
These standard functions are groups in different libraries which can be included in
the C++ program. i.e. In C++, predefined functions are organized into separate
libraries.
Math functions are declared in <math.h> library
Character-manipulation functions are declared in <ctype.h> library
IO function are declared in <iostream>
To use predefined function, include the header file that contains the function’s
specification
via the include statement.
#include <library name>
Some of the predefined mathematical functions are pow(x, y), sqrt(x), and floor(x).
8
`
9
10
Example of Using
Standard C++ Math Functions
To use predefined functions in a program, you must include the header file that
contains the function’s specification via the include statement.
For example, to use the function pow, the program must include:
#include <cmath>
#include <iostream.h>
#include <math.h>
void main()
{
double x;
cout << "Please enter a real number: ";
cin >> x;
// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;
cout << "The square root of(" << x << ") = " << sqrt(x) << endl;
} 11
Example of Using
Standard C++ Character Functions
#include <iostream.h> // input/output handling
#include <ctype.h> // character type functions
void main()
{
char ch;
cout << "Enter a character: "; Explicit casting
cin >> ch;
cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;
cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;
if (isdigit(ch))
cout << "'" << ch <<"' is a digit!\n";
else
cout << "'" << ch <<"' is NOT a digit!\n";
}
12
Example
#include <iostream>
#include <cmath.h> //math.h
#include <cctype> //string
using namespace std;
int main() {
int number=-32; double number1, number2; char ch = ‘C';
cout << " Enter two Number : "; cin >> number1>> number2;
cout << ch<< " a lowercase letter? “ << islower(ch) << endl;
cout << "Uppercase a is "<< static_cast<char>(toupper('a'))<<endl;
cout << number1<< " to the power of " << number2<< " = " << pow(number1, number2)
<<endl;
cout << "Absolute value of " << number << " = " << abs(num) << endl;
cout << "Square root of 36.00 = “ << sqrt(36.00) << endl;
return 0;
} 13
User-Defined Functions
Although C++ is shipped with a lot of standard functions, these functions are not enough
for all users, therefore, C++ provides its users with a way to define their own functions
(or user-defined function).
Once you write and properly debug a function, you can use it without having to rewrite
the same code repeatedly.
User-defined functions in C++ are classified into two categories:
Value-returning functions —functions that have a return type.
These functions return a value of a specific data type using the return statement.
Void functions—functions that do not have a return type.
These functions do not use a return statement to return a value.
We can use value-returning function as a follows:
As an assignment statement. x = pow(3.0, 2.5);
As a parameter in a function call.
As an output statement. cout << abs(-5) <<
14endl;
How to define a C++ Function?
Generally, we define a C++ function in two steps (preferably but not mandatory)
Step #1 – declare the function signature in either a header file (.h file) or
before the main function of the program.
Step #2 – Implement the function in either an implementation file (.cpp) or
after the main function.
A C++ function consists the following properties:
The name of the function.
The number of parameters, if any.
The data type of each parameter.
The data type of the value computed (that is, the value returned) by the
function, called the type of the function.
The code required to accomplish the task.
15
Function Declarations:
18
Cont...
A function definition describes how the function computes the value it returns.
If you think of a function as a small program within your program, then the
function definition is like the code for this small program.
In fact, the syntax for the definition of a function is very much like the syntax
for the main part of a program.
The function header is written the same way as the function declaration,
except that the header does not have a semicolon at the end. This makes the
header a bit repetitious, but that’s OK.
The function body follows the function header and completes the function
definition. The function body consists of declarations and executable
statements enclosed within a pair of braces.
19
Cont…
When the function is called, the argument values are plugged in for the formal
parameters and then the statements in the body are executed.
The value returned by the function is determined when the function executes a
return statement.
A return statement consists of the keyword return followed by an expression.
Consider the definition of the function abs:
20
Calling functions
To do this, the name of the function and any parameters you are passing to it
must be typed out EXACTLY as how the function declared it.
to call a value returning function, you use its name, with the actual parameters (if
any) in parentheses.
In a function call, the number of actual parameters, together with their data
types, must match with the formal parameters in the order given.
22
Returning Values from Functions
24
Cont…
Local Variables.
A variable created in a function is called a local variable.
It exists only locally within the function itself. When the function returns, all of
its local variables are no longer available for use in the program.
Parameters received by the function are also considered local variables.
If a function defines a local variable and there was a global variable with the
same name, the function uses its local variable instead of using the global
variable.
Global variables.
Variables can be defined outside of all functions in a C++ program, including
the main() function.
they are available everywhere in the program.
26
I. Using Global Variables
#include <iostream.h>
int x = 0;
void main()
f2();
27
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
28
Static and Automatic Variables
A variable for which memory is allocated at block entry and deallocated at block
exit is called an automatic variable.
A variable for which memory remains allocated as long as the program executes
is called a static variable.
Global variables are static variables, and by default, variables declared within a
block are automatic variables.
You can declare a static variable within a block by using the reserved word
static.
Because memory for static variables remains allocated between function calls,
static variables allow you to use the value of a variable from one function call to
another function call.
Even though you can use global variables if you want to use certain values from
one function call to another, the local scope of a static variable prevents other
functions from manipulating its value. 29
Example
void test();
int main(){
int count;
for (count = 1; count <= 5; count++)
test();
Sample Run:
return 0;
Inside test x = 2 and y = 11
} Inside test x = 4 and y = 11
void test(){ Inside test x = 6 and y = 11
static int x = 0; Inside test x = 8 and y = 11
int y = 10; Inside test x = 10 and y = 11
x = x + 2;
y = y + 1;
cout << "Inside test x = " << x << " and y = "
<< y << endl;
} 30
Function Parameters
This is what we use to declare in the function signature or function header, e.g.
int max (int x, int y);
Here, parameters x and y are value parameters
When you call the max function as max(4, 7), the values 4 and 7 are copied to
x and y respectively
When you call the max function as max (a, b), where a=40 and b=10, the
values 40 and 10 are copied to x and y respectively
When you call the max function as max( a+b, b/2), the values 50 and 5 are
copies to x and y respectively
Once the value parameters accepted copies of the corresponding arguments data,
they act as local variables!
32
Example of Using Value Parameters and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)//local variable
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
33
Cont…
34
Reference Parameters
As we saw in the last example, any changes in the value parameters don’t affect
the original function arguments.
Sometimes, we want to change the values of the original function arguments or
return with more than one value from the function, in this case we use reference
parameters.
A reference parameter is just another name to the original argument variable
We define a reference parameter by adding the & in front of the parameter
name, e.g.
double update (double & x);
35
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}
36
Example of Reference Parameters
#include<iostream>
using namespace std;
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
39
Cont..
In general, the following rules apply for functions with default parameters:
The caller has the option of specifying a value other than the default for
any default parameter.
You cannot assign a constant value as a default value to a reference
parameter. 40
Example
In C++, more than one function can have the same name as long as there are
differences in their arguments, In this situation, the functions that share the same
name are said to be overloaded, and the process is referred to as function
overloading.
The functions must have different data types for parameters, a different number of
parameters, or both. Here are three prototypes for overloaded functions:
int store(int, int);
int store(long, long);
int store(long);
The secret to overloading is that each redefinition of the function must use either-
different types of parameters or different number of parameters.
Two functions are said to have different formal parameter lists if both functions
have:
A different number of formal parameters or
If the number of formal parameters is the same, then the data type of the formal
parameters, in the order you list them, must
43 differ in at least one position.
Cont…
The return types for overloaded functions do not factor into whether they are
different. Several overloaded functions can have the same return type.
Overloading makes it possible to create a function that performs a similar
task on different types of data without creating unique names for each
function.
averageInts(), averageDoubles(), and averageFloats()
int average(int, int);
long average(long, long);
float average(float, float);
44
Overloading Functions Example
int sum (int a, int b); cout<< "Call of int sum (int a, float b);=
"<< sum (x, p)<< endl;
int sum (int a, float b); cout<< "Call of int sum (float a, int b);=
int sum (float a, int b); "<< sum (p, y)<< endl; return 0;
}
int sum (int a, int b, int c);
int sum (int a, int b) {
int main( ) {
return(a+b); }
int x, y, z; float p; int sum (int a, float b) {
When you define a function, the C++ compiler creates just one set of instructions
in memory.
Execution of the program jumps to those instructions when the function is called
and jumps back after the function returns to the next line in the calling function.
If the program calls the function 10 times, it jumps to the same set of
instructions each time. There only is one copy of the instructions that make up
the function, not 10 copies.
If a C++ function is declared with the keyword inline, the compiler does not
create a real function. Instead, it copies the code from the inline function directly
into the place where the function was called. It is just as if you had written the
statements of the function right there.
inline int double(int);
46
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
47
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0; x 0
#include <iostream.h>
int x = 0; x 4
#include <iostream.h>
int x = 0; x 5
#include <iostream.h>
int x = 0; x 5
#include <iostream.h>
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
52
Recursive Functions
In certain cases, you can actually have a function call itself. Such a
function is called a recursive function.
Direct recursion: When function calls itself, it is called direct recursion
For example: function A calls function A.
Indirect recursion: When function calls another function and that
function calls the calling function, then this is called indirect recursion.
For example: function A calls function B and Function B calls function A.
Note that: recursive function should have a very clearly defined exit
condition where it returns without invoking itself again.
53
Example
54
Indirect Recursion Example in C++
55
Functions and Array
In C++, arrays are passed by reference only. Because arrays are passed by
reference only, you do not use the symbol & when declaring an array as a formal
parameter.
only the address of the first element of the array is passed, not a copy of the
entire array.
Note: In C++, an array name without any index is a pointer to the first array
element. This means that the formal parameter declaration has to be of a
compatible type.
56
Cont…
You can pass array as an argument to a function just like you pass variables
as arguments. In order to pass array to the function you just need to mention
the array name during function call like this:
function_name(array_name);
as an unsized array
as a pointer
57
Passing Arrays (1): with size specification Example
58
Passing Arrays (2): as an unsized array Example
59
Passing Arrays (3): using a pointer
60
Passing Arrays (4): using a pointer and array size information
61
Cont…
63
Cont…
65
Functions and String
68
Example #2
69
Example #3
70
Example #4
Function Overloading
Write functions to return with the maximum number of two
numbers
An overloaded
inline int max( int x, int y) function is a
function that is
{ defined more than
if (x>y) return x; else return y; once with different
data types or
} different number
of parameters
inline double max( double x, double y)
{
if (x>y) return x; else return y;
}
71
Example