Professional Documents
Culture Documents
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?
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
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.
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
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
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;
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
13
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
arguments list
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
arguments list
function name
function header
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
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
Function declaration:
To receive an array of
int, a[] as
argument
Function definition :
Manipulating a[]
inside fill_up
implementation
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
#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;
}
#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
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) {
. . .
}
#include <iostream>
using namespace std;
int main ()
{
int a[row][col];
Read2Array(a);
writing(a);
system(pause);
return 0;
}
#include <iostream>
using namespace std;
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
}
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
#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
#include <iostream>
using namespace std;
int f( int a)
{
if (a<1)
return 1;
else
return a * f(a-1);
}
Recursion
int main()
{
int k=5;
cout << f(k);
return 0;
}
ITPROG2 Module 2 - Functions
#include <iostream>
using namespace std;
Function Headers
#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;
}
Any Questions
46