0% found this document useful (0 votes)
66 views73 pages

Chapter 3 Function

The document discusses different types of functions in C++ including standard functions, user-defined functions, and how to define functions. It provides examples of using standard math and character functions as well as how to declare and implement user-defined functions.

Uploaded by

Demeke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views73 pages

Chapter 3 Function

The document discusses different types of functions in C++ including standard functions, user-defined functions, and how to define functions. It provides examples of using standard math and character functions as well as how to declare and implement user-defined functions.

Uploaded by

Demeke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Jimma University

School of Computing and


Informatics.

Fundamental of Programming II

Chapter Three: Functions.

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

Concepts of breaking down the design of a program into individual components


(modules) that can be programmed and tested independently is called modular
programming.

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.

In programming, this methodology reflects itself in the use of sub-


programs, and in C++ all sub-programs are called functions
(corresponding to both "functions" and "procedures" in Pascal and some
other programming languages).

4
Cont..

Functions are like building blocks. They let you divide complicated
programs into manageable pieces.

They have other advantages, too:

 While working on one function, you can focus on just that part of the
program and construct it, debug it, and perfect it.

 Different people can work on different functions simultaneously.

 If a function is needed in more than one place in a program or in different


programs, you can write it once and use it many times.

 Using functions greatly enhances the program’s readability because it


reduces the complexity of the function main.

5
Function

It is a group of statements that together perform a task on data and returns a
value.

It is Accessed at some point in the execution of a program. It accessed when


it is called.

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

Using functions greatly enhances the program’s readability because it


reduces the complexity of the function main.

6
Cont…

A C++ function or a subprogram is simply a chunk of C++ code that has :-


 A descriptive function name, e.g.
 computeTaxes-to compute the taxes for an employee
 isPrime-to check whether or not a number is a prime number
 A returning value
 The computeTaxes function may return with a double number representing
the amount of taxes
 The isPrime function may return with a Boolean value (true or false)
Why?
 to aid in the conceptual organization of a program.
 to reduce program size.
 different people can work on different functions simultaneously.
In C++, the concept of a function, either predefined/ Standard Functions or
user-defined Function. 7
Predefined/Standard Functions

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:

A function declaration ( prototype or signature) is a single statement, which ends


with a semicolon following parts: i.e The function heading without the body of the
function.
 The syntax of a value-returning function is
functionType functionName(parameter list);
 functionType is the type of the value that the function returns. The functionType
is also called the data type or the return type of the value-returning function.
Eg:int max(int num1, int num2);
int max(int, int);
We place function prototypes before any function definition (including the
definition of main).
Function declaration is required when you define a function in one source file and
you call that function in another file.
In such case, you should declare the function at the top of the file calling the
function.
 16
Cont…

The functions with no return type is must be used of void keywords.


Something that is no optional in the function is the parentheses that follow the
function name, in its declaration or when calling it.
 And even when the function takes no parameters, at least an empty pair of
parentheses shall always be appended to the function name.
if the function has return value there should be at least one return statement that
returns a variable of proper return type.
A function that return type is void does not need a return statement.
Remember: Function Declaration
 A function declaration tells you all you need to know to write a call to the
function.
 A function declaration is required to appear in your code prior to a call to a
function whose definition has not yet appeared.
 Function declarations are normally placed before the main part of your program.
17
Defining a Function:

The general form of a C++ function definition is as follows:


return_type function_name( parameter list )
{
body of the function
}
 Return type: data type of the value the function returns. Eg int, double,
void,string.
 Function name: the actual name of the function.
 Parameters: A parameter is like a placeholder. Parameters are optional.
 Body of the function: The function body contains a collection of statements
that define what the function does.
The syntax of the formal parameter list is:
dataType identifier, dataType identifier, ...

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.

A function definition consists of a function header followed by a function body.

 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 be used function in a program, it must be called.

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.

The syntax to call a value-returning function is:

functionName(actual parameter list)

to call a value returning function, you use its name, with the actual parameters (if
any) in parentheses.

Formal Parameter: A variable declared in the function heading.

Actual Parameter: A variable or expression listed in a call to a function.

In a function call, the number of actual parameters, together with their data
types, must match with the formal parameters in the order given.

 That is, actual and formal parameters have a one-to-one correspondence.


21
Cont..

A function’s formal parameter list can be empty. However, if the formal


parameter list is empty, the parentheses are still needed.
The function heading of the value-returning function thus takes, if the formal
parameter list is empty, the following form:
functionType functionName()
If the formal parameter list of a value-returning function is empty, the actual
parameter is also empty in a function call.
In this case (that is, an empty formal parameter list), in a function call, the empty
parentheses are still needed. Thus, a call to a value-returning function with an
empty formal parameter list is:
functionName()

22
Returning Values from Functions

Functions return a value or void.


To return a value from a function, the keyword return is followed by the value to
return. The value can be a literal, a variable, or an expression, because all
expressions produce a value.
The return statement has the following syntax:
return expr;
in which expr is a variable, constant value, or expression. The expr is evaluated,
and its value is returned. The data type of the value that expr computes must
match the function type.
Here are some examples:
return 5;
return (x > 5);
return (convert(fahrenheit));
When a return statement is executed, program execution returns immediately to
the statement that called the function. Any statements following return are not
executed. 23
Cont…

A function can return a reference, which means, it returns an implicit pointer to


its return value. The function can be used on the left side of an assignment
statement!
double val = 100;
double &f(){
return val; // return reference to val
//cannot return reference to local variable only global variable
}
double newval;
newval = f(); // assign value of val, which is 100
f() = 99.1; // change val´s value reference to val becomes target of assignment
cout<<newval;
cout<<val;

24
Cont…

Here is another example program using a reference return type:

double v[] = {1.1, 2.2, 3.3, 4.4, 5.5};


double &change_element(int i) {
return v[i]; // reference to i-th element
}
void main(){
int i;
for(i=0; i<5; i++) cout << v[i] << ‘ ‘;
change_element(1) = 523.9; // second element
change_element(3) = -98.7; // 4th element
for(i=0; i<5; i++) cout v[i] << ‘ ‘;
}
25
Variables with Functions

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 f1() { x++; }

void f2() { x+=4; f1(); }

void main()

f2();

cout << x << endl;

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

Function receives information in the form of function parameters.


There can be more than one parameter as long as they are separated by commas, or
a function can be called with no parameters at all.
The parameters sent to a function don’t have to be of the same data type.
Two way to pass parameter.
 By Value.
 By Reference.
Passing by Value.
 This will give a COPY of the value to the function and the ORIGINAL value
WILL NOT CHANGE IN THE PROGRAM.
Passing by reference.
 This method of passing values is very different from the first method. Here,
values CAN CHANGE if any of them are being passed by reference.
 In order to denote a pass by reference, an ampersand ( & ) must be placed after
the type of the parameter. 31
Value 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…

int sqr_it(int x);


int main()
{
int t = 10;
cout << sqr_it(t) << ‘ ‘ << t;
return 0;
}
int sqr_it(int x)
{
x = x * x;
return x;
}

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

void swap(int &x, int &y)


{
int temp;
temp = x; // save the value at address x
x = y; // put y into x
y = temp; // put temp, i.e., x, into y
}
int main()
{
int i, j;
i = 10;
j = 20;
cout << “initial values of i and j: “;
cout << i << ‘ ‘ << j << ‘\n’;
swap(i, j);
cout << “swapped values of i and j: “;
cout << i << ‘ ‘ << j << ‘\n’;
return 0;
37
Default Function Parameters

A default argument is a value provided in function declaration that is


automatically assigned by the compiler if caller of the function doesn’t
provide a value for the argument with default value.
 If the function prototype declares a default value for a parameter, the
function can be called without that parameter.
The default value is used whenever the parameter is omitted.
Default arguments are different from constant arguments as constant
arguments can’t be changed whereas default arguments can be overwritten if
required.
A function’s definition does not change when default parameters are declared
in the prototype.
long set4DPoint(int x, int y, int z, int t);
Once default value is used for an argument in function definition, all
subsequent arguments to it must have default value.
long set4DPoint (int x, int y, int z = 1, int t = 2000);
38
Cont..

#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:

 If we do not specify the value of a default parameter, the default value is


used for that parameter.
 All of the default parameters must be the far-right parameters of the
function.
 Suppose a function has more than one default parameter. In a function call,
if a value to a default parameter is not specified, then you must omit all of
the arguments to its right.
 Default values can be constants, global variables, or function calls.

 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

int volume(int l = 1, int w = 1, int h = 1);


void funcOne(int& x, double y = 12.34, char z = 'B');
int main()
{
int a = 23;
double b = 48.78;
char ch = 'M';
cout << "Line 1: a = " << a << ", b = “ << b << ", ch = " << ch << endl;
//Line 1
cout << "Line 2: Volume = " << volume() << endl; //Line 2
cout << "Line 3: Volume = " << volume(5, 4) << endl; //Line 3
cout << "Line 4: Volume = " << volume(34) << endl; //Line 4
cout << "Line 5: Volume = “ << volume(6, 4, 5) << endl; //Line 5
funcOne(a); //Line 6
funcOne(a, 42.68); //Line 7
funcOne(a, 34.65, 'Q'); //Line 8
cout << "Line 9: a = " << a << ", b = “ << b << ", ch = " << ch << endl;
//Line 9
return 0;
} 41
Cont..

int volume(int l, int w, int h)


{
return l * w * h;
}
void funcOne(int& x, double y, char z)
{
x = 2 * x;
cout << "Line 12: x = " << x << ", y = “ << y << ", z = " << z <<
endl;
}
Sample Run:
Line 1: a = 23, b = 48.78, ch = M
Line 2: Volume = 1
Line 3: Volume = 20
Line 4: Volume = 34
Line 5: Volume = 120
Line 12: x = 46, y = 12.34, z = B
Line 12: x = 92, y = 42.68, z = B
Line 12: x = 184, y = 34.65, z = Q
42
Overloading Functions

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) {

cout<<"Enter the three integers"; return(a+b); }


int sum (float a, int b) {
cin>>x>> y>>z;
return(a+b); }
cout<< "Enter one float“;
int sum (int a, int b, int c) { return(a+b+c); }
cin>>p;
cout<< "Call of int sum (int a, int b);= "<< sum (x, y)<< endl;
cout<< "Call of int sum (int a, int b, int c);= "<< sum (x, y, z)<< endl;
45
Inline Functions

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

Inline void f1() { x++; }


Inline void f2() { x+=4; f1();} The inline keyword
instructs the compiler
to replace the function
void main() call with the function
body!
{
f2();
void main()
cout << x << endl; {
1 x+=4;
} x++;
cout << x << endl;
}
48
What Happens When We Use Inline Keyword?

#include <iostream.h>
int x = 0; x 4

Inline void f1() { x++; }


Inline void f2() { x+=4; f1();}
void main()
{
f2();
void main()
cout << x << endl; {
x+=4;
} 2 x++;
cout << x << endl;
}
49
What Happens When We Use Inline Keyword?

#include <iostream.h>
int x = 0; x 5

Inline void f1() { x++; }


Inline void f2() { x+=4; f1();}
void main()
{
f2();
void main()
cout << x << endl; {
x+=4;
} x++;
3 cout << x << endl;
}
50
What Happens When We Use Inline Keyword?

#include <iostream.h>
int x = 0; x 5

Inline void f1() { x++; }


Inline void f2() { x+=4; f1();}
void main()
{
f2();
void main()
cout << x << endl; {
x+=4;
} x++;
cout << x << endl;
4 }
51
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;
}

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

//example on Direct recursive functions : factorial calculator


int factorial (int a){ If the user enter for eg. 4, then the stack
frames for these calls appear sequentially on
if (a > 1) the runtime stack, one after the other. Here is
return (a * factorial (a-1)); how it works:
Step 1: Factorial(4)
else Step 2: 4 * Factorial(3)
return (1);} Step 3: 4 * 3 * Factorial(2)
Step 4: 4 * 3 * 2 * Factorial(1)
void main (){ Step 5: 4 * 3 * 2 * 1
int num; Step 6: 4 * 3 * 2
Step 7: 4 * 6
cout << "Type a number: "; Step 8: 24
cin >> num;
The output will be:
cout << num <<"!“ << " = " << factorial (num); Type a number: 4
} 4! = 24

54
Indirect Recursion Example in C++

int fa(int); int main(){


int num=5;
int fb(int); cout<<fa(num);
int fa(int n){ return 0;
}
if(n<=1) return 1;
else return n*fb(n-1);
}
int fb(int n){
if(n<=1) return 1;
else
return n*fa(n-1);
}

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.

When declaring a one-dimensional array as a formal parameter, the size of the


array is usually omitted. If you specify the size of a one-dimensional array when
it is declared as a formal parameter, the size is ignored by the compiler.

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);

There are three ways to declare a parameter that is to receive an array


pointer:
 as an array of the same type and size as that used to call the function

 as an unsized array

 as a pointer

The following three example programs illustrate these three possibilities.

57
Passing Arrays (1): with size specification Example

void display(int n[10]);


int main()
{
int t[10], i;
for(i=0; i<10; ++i) t[i] = i;
display(t); // pass array t to function
return 0;
}
void display(int n[10])
{
int i;
for(i=0; i<10; i++) cout << n[i] << ‘ ‘;
}

58
Passing Arrays (2): as an unsized array Example

void display(int n[]);


int main()
{
int t[10], i;
for(i=0; i<10; ++i) t[i] = i;
display(t); // pass array t to function
return 0;
}
void display(int n[])
{
int i;
for(i=0; i<10; i++) cout << n[i] << ‘ ‘;
}

59
Passing Arrays (3): using a pointer

void display(int *n);


int main()
{
int t[10], i;
for(i=0; i<10; ++i) t[i] = i;
display(t); // pass array t to function
return 0;
}
void display(int *n)
{
int i;
for(i=0; i<10; i++) cout << n[i] << ‘ ‘;
}

60
Passing Arrays (4): using a pointer and array size information

void display(int *n, int s);


int main()
{
int t[10], i;
for(i=0; i<10; ++i) t[i] = i;
display(t, 10);
return 0;
}
void display(int *n, int s)
{
int i;
for(i=0; i<s; i++)
cout << n[i] << ‘ ‘;
}

61
Cont…

Important to remember: As for arrays, only addresses are passed to a


function, the function will potentially alter the contents of the array.
void cube(int *n, int num)
{
while(num) {
*n = *n * *n * *n;
num--;
n++;
}}
void main()
{
int i, nbs[10];
for(i=0;i<10;i++) nbs[i] = i+1;
cube(nbs,10);
for(i=0;i<10;i++) cout << nbs[i] << ‘ ‘;}
62
Functions and Pointers

A pointer variable can be passed as a parameter to a function either by value


or by reference.
To declare a pointer as a value parameter in a function heading, you use the
same mechanism as you use to declare a variable.
To make a formal parameter be a reference parameter, you use & when you
declare the formal parameter in the function heading.
Therefore, to declare a formal parameter as a reference pointer parameter,
between the data type name and the identifier name, you must include * to
make the identifier a pointer and & to make it a reference parameter.
In C++, to make a pointer a reference parameter in a function heading, *
appears before the & between the data type name and the identifier.

63
Cont…

void funponiter(int *pValue)


{
*pValue = 6;
}
int main()
{
int nValue = 5;
cout << "nValue = " << nValue << endl;
funponiter (&nValue);
cout << "nValue = " << nValue << endl;
return 0;
}
64
Cont…

void funpointer(int* &p){


*p=10;
}
int main(){
int x=3;
int* q=&x;
cout<<"Before calling"<<x<<endl;
funpointer(q);
cout<<"After calling "<<x;
}

65
Functions and String

C-Strings are simply character arrays that are null-terminated.


When a string is passed to a function, only a pointer to the beginning of the string
(of type char *) is actually passed.
The following code fragment defines a function that converts strings to uppercase:
void stringToUpper(char *str);
int main()
{
char str[80];
strcpy(str, “this is a test”);
stringToUpper(str);
cout << str;
return 0; }
void stringToUpper(char *str)
{
while(*str) {
*str = toupper(*str); // one character
str++; /* move on to next char */ }
} 66
Cont..

In general, the following rules apply when an identifier is accessed:


Global identifiers (such as variables) are accessible by a function or a block if:
 The identifier is declared before the function definition (block).
 The function name is different than the identifier.
 All parameters of the function have names different than the name of the
identifier.
 All local identifiers (such as local variables) have names different than the
name of the identifier.
(Nested Block) An identifier declared within a block is accessible:
 Only within the block from the point at which it is declared until the end of the
block.
 By those blocks that are nested within that block if the nested block does not
have an identifier with the same name as that of the outside block (the block
that encloses the nested block). 67
Example #1

Write a function to test if a number is an odd number

inline bool odd (int x)


{
return (x % 2 == 1);
}

68
Example #2

Write a function to compute the distance between two


points (x1, y1) and (x2, y2)

Inline double distance (double x1, double y1,


double x2, double y2)
{
return sqrt(pow(x1-x2,2)+pow(y1-y2,2));
}

69
Example #3

Write a function to compute n!

int factorial( int n)


{
int product=1;
for (int i=1; i<=n; i++) product *= i;
return product;
}

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

//Example : Reference and value parameters


void funOne(int a, int& b, char v);
void funTwo(int& x, int y, char& w);
int main(){
int num1=10, num2=15;
char ch = 'A';
cout << "Line 4: Inside main: num1 = " << num1 << ", num2 = " << num2 <<
", and ch = “ << ch << endl; //Line 4
funOne(num1, num2, ch); //Line 5
cout << "Line 6: After funOne: num1 = " << num1 << ", num2 = " << num2
<< ", and ch = “ << ch << endl; //Line 6
funTwo(num2, 25, ch); //Line 7
cout << "Line 8: After funTwo: num1 = " << num1 << ", num2 = " << num2
<< ", and ch = “ << ch << endl; //Line 8
return 0;
} 72
Example

void funOne(int a, int& b, char v)


{
int one;
one = a; //Line 9
a++; //Line 10
b = b * 2; //Line 11
v = 'B'; //Line 12
cout << "Line 13: Inside funOne: a = " << a << ", b = " << b << ", v = " << v << ",
and one = " << one << endl; //Line 13
}
void funTwo(int& x, int y, char& w)
{
x++; //Line 14
y = y * 2; //Line 15
w = 'G'; //Line 16
cout << "Line 17: Inside funTwo: x = " << x << ", y = " << y << ", and w = " << w
<< endl; //Line 17
} Sample Run:
Line 4: Inside main: num1 = 10, num2 = 15, and ch = A
Line 13: Inside funOne: a = 11, b = 30, v = B, and one = 10
Line 6: After funOne: num1 = 10, num2 = 30, and ch = A
Line 17: Inside funTwo: x = 31, y = 50, and w = G
Line 8: After funTwo: num1 = 10, num2 = 31, and ch = G
73

You might also like