Lecture # 10

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Functions

Lecture # 10
Course Instructor:
Dr. Afshan Jamil
Outline
Passing arrays
Predefined
C++ functions as function
functions
arguments

Parameters
Pass by
and Pass by value
reference
arguments

Overloading
Function calling Bool as return
function
another function type
name

Alternate form
void Points to
of function Examples
functions remember
declaration
Passing arrays as function
arguments
• In C++, we can pass arrays as an argument to
a function and also, we can return arrays
from a function.
• Syntax:
returnType functionName(dataType
arrayName[arraySize])
{
// code
}
Passing 1-D array as an argument
// C++ Program to average of marks of 5
students
#include <iostream>
using namespace std;
// declare function to display marks
void average(int[]);
int main()
{
// declare and initialize an array
int marks[5] = { 88, 76, 90, 61, 69 };
average(marks);
return 0;
}
CONTD…
void average(int m[5])
{
int sum=0
for (int i = 0; i < 5; ++i)
{
sum=sum+m[i];
}
cout<<“Average marks=“<<sum/5;
}
Passing 2-D array as an argument
// C++ Program to display the elements of
two-dimensional array.
#include <iostream>
using namespace std;
void display(int[][2]);
int main()
{
int num[3][2] = { {3, 4}, {9, 5}, {7, 1} };
display(num);
return 0;
}
CONTD…
void display(int n[][2])
{
cout << "Displaying Values: " << endl;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 2; ++j)
{
cout << "num[" << i << "][" << j << "]:
" << n[i][j] << endl;
}
}
}
Parameters and arguments
• The formal parameters for a function are
listed in the function declaration and are
used in the body of the function definition. A
formal parameter is a kind of blank or place
holder that is filled in with something when
the function is called.
CONTD…

• An argument is something that is used to


fill in a formal parameter. When you write
down a function call, the arguments are
listed in parentheses after the function
name. When the function call is executed,
the arguments are “plugged in” for the
formal parameters.
• The terms call-by-value and call-by-
reference refer to the mechanism that is
used in the “plugging in” process.
CONTD…
• In the call-by-value method, only the value
of the argument is used. In call-by-value
mechanism, the formal parameter is a local
variable that is initialized to the value of the
corresponding argument.
• In the call-by-reference mechanism, the
argument is a variable, and the entire
variable is used. In the call-by-reference
mechanism, the argument variable is
substituted for the formal parameter so that
any change that is made to the formal
parameter is made to the argument variable.
Difference between pass by
value and reference
call by value call by reference
This method copy original This method copy address of
value into function as arguments into function as
arguments. arguments.
Changes made to the
Changes made to the
parameter affect the
parameter inside the
argument. Because address
function have no effect on
is used to access the actual
the argument.
argument.
Actual and formal arguments Actual and formal arguments
will be created in different will be created in same
memory locations. memory location.
Call by reference parameter

• To make a formal parameter a call-by-


reference parameter, append the
ampersand sign & to its type name.
• The corresponding argument in a call to the
function should then be a variable, not a
constant or other expression.
• When the function is called, the
corresponding variable argument (not its
value) will be substituted for the formal
parameter.
CONTD…
• Any change made to the formal parameter
in the function body will be made to the
argument variable when the function is
called.
• Example:
• int add(int& num1, int& num2);
CONTD…
• void get_numbers(int& input1, int& input2);
• int main():
• {
• int first_num = 0, second_num = 0;
• get_numbers(first_num, second_num);
• }
Example 1
#include<iostream>
using namespace std;
//Function declaration
void add10(int&);
int main()
{
int num;
cout << "Enter a number:";
cin >> num;
cout << "\nNumber before function
call=" << num;
add10(num);
CONTD…
cout << "\nNumber after call by
reference call=" << num;
return 0;
}
//Function definition
void add10(int& a)
{
a = a + 10;
}
Example 2
#include<iostream>
using namespace std;
//Function declaration
void swap(int&, int&);
int main()
{
int num1, num2;
cout << "Enter two numbers:";
cin >> num1>>num2;
cout << "\nNumber before swap=" <<
num1<<" and "<<num2;
swap(num1,num2);
CONTD…
cout << "\nNumber after swap=" <<
num1<<" and "<<num2;
return 0;
}
//Function definition
void swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Functions calling functions
• A function body may contain a call to
another function.
CONTD…
• These sorts of function calls is the same as
it would be if the function call had
occurred in the main function of the
program; the only restriction is that the
function declaration should appear before
the function is used.
• Although you may include a function call
within the definition of another function,
you cannot place the definition of one
function within the body of another
function definition.
Example 3
#include<iostream>
using namespace std;
//Function declaration
float average(int a[]);
int add(int a[]);
int main()
{
int a[10];
cout << "Enter 10 elements:";
for (int i = 0; i < 10; i++)
cin >> a[i];
float avg = average(a);
CONTD…
cout << "\nAverage of array is= " <<
avg;
return 0; }
//Function definition
float average(int a[])
{ int sum = add(a);
float avg = sum / 10;
return avg; }
int add(int b[])
{ int sum = 0;
for (int i = 0; i < 10; i++)
sum = sum + b[i];
return sum; }
Local, Global and block scope
Overloading a function name
• If you have two or more function definitions
for the same function name, that is called
overloading.
CONTD…
• When you overload a function name, the
function definitions must have different
numbers of formal parameters or some
formal parameters of different types.
• When there is a function call, the compiler
uses the function definition whose number
of formal parameters and types of formal
parameters match the arguments in the
function call.
Example
function overloading
int avg(int, int); •

double avg(double,double);
double avg(int, int, int);
int main()
{
int a=3, b=4, c=5;
float f1=2.3, f2=3.5;
cout<<"\nAverage of two integers="<<avg(a,b);
cout<<"\nAverage of two decimal numbers="<<avg(f1,f2);
cout<<"\nAverage of three integeres="<<avg(a,b,c);
}
CONTD…
int avg(int a, int b)
{
return (a+b)/2; }
double avg(double a, double b)
{
return (a+b)/2; }
double avg(int a, int b, int c)
{
return (a+b+c)/3; }
Example
Case Study

• Pizza sizes are given as the diameter of the pizza


in inches. However, the quantity of pizza is
determined by the area of the pizza, and the area
is not proportional to the diameter. Most people
cannot easily estimate the difference in area
between a 10-inch pizza and a 12-inch pizza and
so cannot easily determine which size is the best
buy—that is, which size has the lowest price per
square inch. In this case study we will design a
program that compares two sizes of pizza to
determine which is the better buy.
CONTD..
• A pizza is basically a circle (made up of
bread, cheese, sauce, and so forth). The
area of a circle (and hence of a pizza) is πr
2, where r is the radius of the circle and π
is the number called “pi,” which is
approximately equal to 3.14159. The
radius is one half of the diameter.
CONTD…
• Input
The input will consist of the diameter in
inches and the price for each of two sizes of
pizza.
• Output
The output will give the cost per square inch
for each of the two sizes of pizza and will tell
which is the better buy, that is, which has the
lowest cost per square inch.
CONTD…
• Subtask 1: Get the input data for both the
small and large pizzas.
• Subtask 2: Compute the price per square
inch for the small pizza.
• Subtask 3: Compute the price per square
inch for the large pizza.
• Subtask 4: Determine which is the better
buy.
• Subtask 5: Output the results.
THE END

You might also like