Lecture # 10
Lecture # 10
Lecture # 10
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…
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