You are on page 1of 46

ITPROGX2

Module 2
Functions

Objectives
To learn about functions
Explore how to declare and manipulate functions
Differentiate formal parameters from actual
parameters
Differentiate call-by-value and call-by-reference
Explore how to implement functions with arrays
Explore how to implement function overloading

Functions
What is a function?

Function is a self contained block of statements


that perform a coherent task of some kind.
Every C++ program can be a thought of the
collection of functions.
main( ) is also a function.
3

Why use functions?


Writing functions avoids rewriting of the same
code again and again in the program.
Using function large programs can be reduced
to smaller ones. It is easy to debug and find
out the errors in it.
Using a function it becomes easier to write
program to keep track of what they are doing.

Types of functions
Library functions (Predefined functions)
These are the in- -built functions of C++ library.
These are already defined in header files.
e.g. sqrt( )is a function which is used compute the
square root of a value. It is defined in cmath.h
file .
User defined functions.
Programmer can create their own function in C++
to perform specific task

Predefined Functions

//Computes the size of a dog house that can be purchased given the
//users budget
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const double COST_PER_SQ_FT = 10.50;
double budget, are, length_side;
cout << "Enter rhe amount budgeted for your dog house $";
cin >> budget;
area = budget/COST_PER_SQ_FT;
length_side = sqrt(area);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "For a price of $" << budget << endl
<< "I can build for you a luxurious square dog house\n"
<< "that is " << length_side
<< "feet on each side.\n"; Enter the amount budgeted for your dog house: $ 25.00

For a price of $ 25.00


return 0;
I can build you a luxurious square dog house
ITPROG2 Module 2 - Functions that is 1.54 feet on each side. 7

Programmer-Defined Functions
We can define our own functions, either in the
same file as the main part of our program of in a
separate file so that the functions can be used by
several different programs.

ITPROG2 Module 2 - Functions

Functions
There are two components to define a function:
1. Function declaration (or function prototype)
* Shows how the function is called
* Must appear in the code before the function can be called
* Normally placed before the main part of your program
2. Function definition (or function body)
* Describes how the function does its task
* Can appear before or after the function is called
* Normally placed after the main part of your program or in
a separate file.

Function Declaration

Syntax:
data_type Function_Name(Parameter_List);

parameter list
data type function name parameters type

formal parameters name

double total(int number, double price);


// Compute total cost including 5% sales tax on
// number_par items at cost of price_par each

10

Function Definition

Syntax:
data_type Function_Name(Parameter_List);
function header
double total(int number, double price)
{
double tax= 0.05;
double subtotal;

function
body

subtotal= number * price_par - tax;


return subtotal;
}

return statement
11

function declaration

#include <iostream>
using namespace std;
double total_cost(int number_par, double price_par);
//Computes the total cost, including 5% sales tax, on number_par
//items at a cost of price_par each.
int main()
{
double price, bill;
int number;
cout << "Enter the number of items purchased: ";
cin >> number;
cout << "Enter the price per item $";
cin >> price;
bill = total_cost(number, price);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << number << " items at "
<< "$" << price << " each.\n
<< "Final bill, including tax, is $" << bill
<< endl;
}

return 0;

double total_cost(int number_par, double price_par)


{
const double TAX_RATE = 0.05; //5% sales tax
double subtotal;

ITPROG2
Module 2 - Functions
subtotal = price_par * number_par;

function call
Enter the number of items purchased: 2
Enter the price per item: $10.10
2 items at $10.10 each.
Final bill, including tax, is $21.21

function heading

function body

12

function
definition

The Return Statement

A return statement consists of the keyword return followed by


an expression.

When a return statement is executed, the function call ends

Returns the value calculated by the function

A void function is does not necessarily contain a return


statement, however it may optionally have one or more return
statement.

13

The Return Statement

Syntax
return expression;
expression performs the calculation
or
expression is a variable containing the calculated value

Example
return (subtotal + subtotal * tax);
or
return subtotal + subtotal * tax;

14

Function Call
A function call is an expression consisting of the
function name followed by arguments enclosed in
parentheses.
If there is more than one argument, the arguments are
separated by commas.
A function call is an expression that can be used like
any other expression of the type specified for the
value returned by the function.

15

The Function Call


Syntax
Function_Name(Argument_List);
where the Argument_list is a comma-separated list of arguments:
Argument_1, Argument_2, . . ., Argument_Last
Examples
function name

arguments list

bill = total(number, price);


return value assigned to bill
16

Void-Function
What is a void-function?
Subtasks are implemented as functions in C++.
In C++, a function must either return a single
value or return no values at all.
A function that returns no value is called a void
function.

17

Void-Function
void Function_Name(Parameter_List);
There are two main differences between void-function
definitions and the definitions of functions that return one value:
1. Keyword void replaces the data type of the function
2. No return statement

18

Syntax for a void Function Declaration


void Function Declaration
void Function_Name(Parameter_List);
Function_Declaration_Comment

arguments list

function name

print (average, min, max);

void Function Definition


void Function_Name(Parameter_List)
{
Declaration_1
Declaration_2
body
...
Declaration_Last
Executable_Statement_1
Executable_Statement_2
...
Executable_Statement_Last
}

function header

void print (int number, double price)


{
double tax= 0.05;
double subtotal;
subtotal= number * price_par tax;
cout << subtotal;
}

19

Categories of functions
A function with no parameter and no return value
A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value

A function with no parameter and no return value

A function with parameter and no return value

A function with parameter and return value

A function without parameter and return value

Arrays in Function
Indexed variables can be arguments to functions
Example: If a program contains these declarations:
int i, n, a[10];
void my_function(int n);
Variables a[0] through a[9] are of type int, making
these calls legal:
my_function( a[ 0 ] );
my_function( a[ 3 ] );
my_function( a[ i ] );
ITPROG2 Module 2 - Functions

Array as Function Arguments


A formal parameter can be for an entire array
Such a parameter is called an array parameter
It is not a call-by-value parameter
It is not a call-by-reference parameter
Array parameters behave much like call-byreference parameters

ITPROG2 Module 2 - Functions

Array Parameter Declaration


An array parameter is indicated using empty
brackets in the parameter list such as
void fill_up(int a[ ], int size);

ITPROG2 Module 2 - Functions

Function with an Array Parameter


#include<iostream>
using namespace std;
void fill_up(int a[], int size);
//Precondition: size is the declared size of the array a.
// The user will type in size integers.
//Postcondition: The array a is filled with size integers
// from the keyboard.
void fill_up(int a[], int size)
{
cout << "Enter " << size << " numbers:\n";
for (int i = 0; i < size; i++)
cin >> a[i];
size--;
cout << "The last array index used is " << size << endl;
}

ITPROG2 Module 2 - Functions

Function declaration:
To receive an array of
int, a[] as
argument

Function definition :
Manipulating a[]
inside fill_up
implementation

Function calls with array


If function fill_up is declared in this way:
void fill_up(int a[ ], int size);

and array score is declared this way:


int score[5], number_of_scores;

fill_up is called in this way:


fill_up(score, number_of_scores);

ITPROG2 Module 2 - Functions

Function call details


A formal parameter is identified as an array
parameter by the [ ]'s with no index expression
void fill_up(int a[ ], int size);

An array argument does not use the [ ]'s


fill_up(score, number_of_scores);

ITPROG2 Module 2 - Functions

Array Formal Parameters


An array formal parameter is a placeholder for
the argument
When an array is an argument in a function call,
an action performed on the array parameter is
performed on the array argument
The values of the indexed variables can be
changed by the function
ITPROG2 Module 2 - Functions

Array Parameter Considerations


Because a function does not know the size of
an array argument
The programmer should include a formal parameter
that specifies the size of the array
The function can process arrays of various sizes
Function fill_up can be used to fill an array of any
size:
fill_up(score, 5);
fill_up(time, 10);
ITPROG2 Module 2 - Functions

Returning An Array
Recall that functions can return a value of
type int, double, char, , or a class type
Functions cannot return arrays
We learn later how to return a pointer to an array

ITPROG2 Module 2 - Functions

#include <iostream>
using namespace std;
void ReadArray(int arr[] ) {
int i;
for (i=0; i < 9; i++)
{ cout << "a["<<i<<"]=";
cin >> arr[i];
}
}

To read 9 numbers
int main() {
int i;
int a[9];
ReadArray(a);
for (i=0; i < 9; i++)
cout << a[i] << '\t';
system(pause);
return 0;
}

ITPROG2 Module 2 - Functions

#include <iostream>
using namespace std;
void ReadArray(int arr[] ) {
int i;
for (i=0; i < 9; i++)
{ cout << "a["<<i<<"]=";
cin >> arr[i];
}
}
// Bubble sort
void sorting(int arr[] ) {
int i, j, temp;
for (i=0; i < 9; i++)
for (j=0; j < 8; j++)
if (arr[j] > arr[j+1])
{ temp= arr[j];
arr[j]= arr[j+1];
arr[j+1]= temp;
}
}
ITPROG2 Module 2 - Functions

To read 9 numbers, then sort them in


ascending order
int main() {
int i;
int a[9];
ReadArray(a);
for (i=0; i < 9; i++)
cout << a[i] << '\t';
cout << endl;
sorting(a);
for (i=0; i < 9; i++)
cout << a[i] << '\t';
system(pause);
return 0;
}

Functions and
Multidimensional Array
When a one-dimensional array is defined as
a formal parameter, the size of the array
may be omitted
void Fun(float list[], int size) {
. . .
}

ITPROG2 Module 2 - Functions

Multi Dimensional Array as Parameter


With two-dimensional arrays, the first dimension (number of rows)
may be omitted, but not the second dimension (number of columns).
void Fun(float table[ ][5], int rows, int cols)
{
. . .
}
You can specify both dimensions if you choose to.
void Fun(float table[2][5], int rows, int cols)
{
. . .
}

ITPROG2 Module 2 - Functions

#include <iostream>
using namespace std;

To populate two dimensional


array then display its elements

const int row=3;


const int col=4;
void Read2Array(int arr[][col] ) {
int i,j;
for (i=0; i<row; i++)
for ( j=0; j<col; j++)
cin >> arr[i][j];
}
void writing(int arr[][col]) {
int i,j;
for (i=0; i<row; i++)
{
for ( j=0; j<col; j++)
cout << arr[i][j] << '\t';
cout << endl;
}
}
ITPROG2 Module 2 - Functions

int main ()
{
int a[row][col];
Read2Array(a);
writing(a);
system(pause);
return 0;
}

#include <iostream>
using namespace std;

To multiply two arrays

void multi(int a[][3], int b[][4], int c[][4]) {

int main ()
{
int x[3][3]= {{12, 4, 9}, { -5, 3,
1}, { 9, 2, -2}};

int i, j, k;
for (i=0; i<3; i++)
for ( j=0; j<4; j++)
{
c[i][j]=0;
for ( k=0; k<3; k++)
c[i][j]= c[i][j] + a[i][k] * b[k][j];
}
}
void writing(int arr[][4]) {
for (int i=0; i<3; i++)
{
for ( int j=0; j<4; j++)
cout << arr[i][j] << '\t';
cout << endl;
}
ITPROG2
Module 2 - Functions
}

int y[3][4]= {{11, 1, 12, 1},{ 2,


24, 32, 4}, {63, -3, 3, 4}} ;
int z[3][4];
multi(x, y, z);
writing(z);
system(pause);
return 0;
}

Function Overloading
Function overloading (aka function polymorphism) allows functions in C++ to share the same name
For example, imagine that we have a sorting algorithm that we wish to use to implement functions
for several types, such as int and char
Traditionally, we would have to use different names for these functions

Overloaded functions are


distinguished
by a[])
their argument
void
sortint(int
{}list

void sortchar(char a[]) {}

void sort(int a[])


{}
void sort(char a[]) {}

ITPROG2 Module 2 - Functions

#include <iostream>
using namespace std;
int add( int A, int B )
{
return A+B;
}
int add( int A )
{
return A;
}
int add( float A, float B )
{
return A+B;
}

int main()
{
int i1=2, i2=7;
float f1=3, f2=5;
cout << add(i1, i2) << endl;
cout << add(i1) << endl;
cout << add(f1, f2) << endl;
system ("pause");
return 0;
}
9
2
8

ITPROG2 Module 2 - Functions

ITPROG2 Module 2 - Functions

#include <iostream>
using namespace std;
int f( int a)
{
if (a<1)
return 1;
else
return a * f(a-1);
}

Recursion

A function definition may contain a call


to the function being defined.

int main()
{
int k=5;
cout << f(k);
return 0;
}
ITPROG2 Module 2 - Functions

#include <iostream>
using namespace std;

Function Headers

int sum(int x, int y) {


int s;
s=x+y;
return s;
}
void print(int x) {
cout << x;
}
int main () {
int v;
v=sum (3, 5);
print(v);
return 0;
}
ITPROG2 Module 2 - Functions

#include <iostream>
using namespace std;
int sum(int , int );
void print(int );
int main () {
int v;
v=sum (3, 5);
print(v);
return 0;
}
int sum(int x, int y) {
int s;
s=x+y;
return s;
}
void print(int x) {
cout << x;
}

Call by-reference parameter


To make a formal parameter a call-by-reference parameter, append
the ampersand sign, &, to its type name

ITPROG2 Module 2 - Functions

Any Questions

46

You might also like