You are on page 1of 27

12/02/2016

W02
Review of C++ - Functions

Function Definition
Function Prototype
Function Calls
Default Parameters
Overloaded Functions
Inline Functions
Recursion
2

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 1
12/02/2016

Functions

W02-Review of C++
3

Functions

 A function is a group of statements that


together perform a task.

 Using functions we can structure our


programs in a more modular way.

W02-Review of C++
4

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 2
12/02/2016

Function Definition

type name ( parameters) { statements }

 type is the data type specifier of the data returned by the


function.
 name is the identifier by which we call the function.
 parameters (as many as needed): Each parameter
consists of a data type specifier followed by an identifier,
(for example: int x)
 statements is the function's body.

W02-Review of C++
5

Function Input & Output

W02-Review of C++
6

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 3
12/02/2016

An Example

int add2nums(int first, int second)


{
return(first+second);
}

W02-Review of C++
7

Example: Using a Function


int add2nums( int first, int second)
{
return(first + second);
}
int main(void) {
int y,a,b;
cout << "Enter two numbers:\n";
cin >> a >> b;
y = add2nums(a,b);
cout << “First number = " << a << endl;
cout << “Second number = " << b << endl;
cout << “Sum = " << y << endl;
return 0;
}

W02-Review of C++
8

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 4
12/02/2016

Function Prototypes

 A function prototype specifies the function


name, return type and parameter types.

 Examples:

double sqrt(double);
int add2nums(int, int);
int counter(void);

W02-Review of C++
9

Using a Prototype
int counter(void);

int main(void) {
cout << counter() << endl;
cout << counter() << endl;
cout << counter() << endl;
}

int counter(void) {
static int count = 0;
count++;
return(count);
}

W02-Review of C++
10

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 5
12/02/2016

Function Calls

Function Call-by-Value
 The value of a variable is passed in
 Caller sends a copy of data value.
 Any change in data value is not visible in caller.

Function Call-by-Reference
 The reference to a variable is passed in.
 The function can change callers variables directly.
 This change is visible in the caller.

W02-Review of C++
11

Function Call-by-Value Example


int subtraction (int a, int b)
{
int r; int main ()
a= 2*a; {
r=a-b; int x=5, y=3, z;
return r; z = subtraction (7,2);
} cout << "The result is " << z << '\n';
cout << "The result is " << subtraction
(x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The result is " << z << '\n';
return 0;
}

W02-Review of C++ 12

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 6
12/02/2016

References

 A reference variable is a shortcut for a


variable.

 A reference variable must be initialized to


reference another variable.

W02-Review of C++
13

Reference Variable Declarations

 To declare a reference variable you precede


the variable name with a “&”:

int &first;
double &last;
char &c;

W02-Review of C++
14

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 7
12/02/2016

Using a Reference Variable

int count;
int &c = count;
// c is the same variable as count

count = 1;
cout << “c is “ << c << endl;
c++;
cout << “count is “ << count << endl;

W02-Review of C++
15

Reference Parameters

 Reference parameters are declared using &


operator:

void add10(int &x) {


x = x+10;
}

add10(counter);

W02-Review of C++
16

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 8
12/02/2016

Function Call by Reference Example


void duplicate (int &a, int &b, int &c)
{
a *= 2;
b *= 2;
c *= 2;
}

int main ()
{
int x = 1, y = 3, z = 7;
duplicate (x, y, z);
cout << "x =" << x << ", y =" << y << ", z =" << z;
return 0;
}

W02-Review of C++
17

Another Reference Example

void swap( int &x, int &y) {


int tmp;
tmp = x;
x = y;
y = tmp;
}

W02-Review of C++
18

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 9
12/02/2016

Default Parameters

 Function call with omitted parameters


 If not enough parameters, rightmost go to their
defaults
 Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
 myFunction(3)
 x = 3, y and z get defaults (rightmost)
 myFunction(3, 5)
 x = 3, y = 5 and z gets default

W02-Review of C++
19

Default Parameters
int divide (int a, int b=2)
{
int r;
r = a/b;
return (r);
}

int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}
W02-Review of C++
20

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 10
12/02/2016

Overloaded Functions

 Functions with same name but different


signatures
 The signature includes the number, type and
order of the parameters, the return type is not
part of the signature
 Should perform similar tasks
int square( int x) {return x * x;}
float square(float x) { return x * x; }

W02-Review of C++
21

Overloaded Functions Example

int operate (int a, int b)


{
float operate(float a, float b, float c)
return (a*b);
{
}
return (a*b*c);
}
int main ()
{
int x=5,y=2;
float l = 6.7, n=5.0, m=2.0;
cout << operate (x,y) << endl;
cout << operate (l, n, m) << endl;
return 0;
}

W02-Review of C++
22

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 11
12/02/2016

Inline Functions

 inline requests the compiler to copy code


into program instead of making function call
 Reduce function-call overhead
 Good for small, often-used functions

 Example
inline double cube( double s )
{ return s * s * s; }

W02-Review of C++
23

Inline Function Example

inline int max(int n1, int n2)


{
return (n1 > n2) ? n1 : n2;
}

int main() {
int i1 = 5, i2 = 6;
cout << max(i1, i2) << endl;
return 0;
}

W02-Review of C++
24

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 12
12/02/2016

Recursion
 Functions can call themselves! This is called
recursion.

 Example:
long int factorial( int x ) {
if (x == 1)
return(1);
else
return(x * factorial(x-1));
}

W02-Review of C++
25

Designing Recursive Functions

 Define “Base Case”:


 The situation in which the function does not call
itself.

 Define “Recursive Case”:


 Compute the return value with the help of the
function itself.

W02-Review of C++
26

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 13
12/02/2016

Recursion

 Recursion is very useful – it’s often very


simple to express a complicated
computation recursively.

W02-Review of C++
27

W02
Review of C++ - Arrays

Declaring, initializing and


using Arrays
Passing Arrays to Functions
2D Arrays
C++ Examples
28

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 14
12/02/2016

W02-Review of C++
29

Arrays

 An array is a collection of elements of similar


data type.

 Array elements are allocated consecutive


memory locations.

W02-Review of C++
30

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 15
12/02/2016

Arrays in Memory
4 bytes

num[0]

num[1]
int num[6];

num[5]

W02-Review of C++
31

C++ Arrays start at 0

 The first element is the 0th element!

 If you declare an array of n elements, the last


one is number n-1.

 If you try to access element number n it is an


error!

W02-Review of C++
32

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 16
12/02/2016

Array Subscripts

 The element numbers are called subscripts.


num[i]

A subscript can be any integer expression:


These are all valid subscripts:
num[17] num[i+3] num[a+b+c]
W02-Review of C++
33

C++ does not have bounds checking


Memory
int a[6];
int n;
a[0]
a[1]
This is the array a[2]
a[3]
a[4]
a[5]
This is something else n

W02-Review of C++
34

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 17
12/02/2016

Declaring An Array

elementType arrayName[numberOfElements];

 elementType can be any C++ variable type.

 arrayName can be any valid variable name.

 numberOfElements can be an int or an expression.

W02-Review of C++
35

Array Example
int factorial( int n ) {
if (n == 1)
return(1);
int main(void) { else
int facs[10]; return(n * factorial(n-1));
}
for (int i=0;i<10;i++)
facs[i] = factorial(i);

for (int i=0;i<10;i++)


cout << "factorial(" << i << ") is " <<
facs[i] << endl;
}
W02-Review of C++
36

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 18
12/02/2016

Initialization
 You can initialize an array when you declare it:

int num[5] = { 1,8,3,6,12};

double d[2] = { 0.707, 0.707};

char s[] = { 'R', 'P', 'I' };

You don’t need to specify a size when initializing,


the compiler will count for you.
W02-Review of C++
37

Passing Array to Function

void printArray(int A[], int len) {


for (int i=0;i<len;i++)
cout << "[" << i << "] = "
<< A[i] << endl;
}

Arrays are always passed by reference


W02-Review of C++
38

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 19
12/02/2016

2D Arrays

char A[3][4];

Col 0 Col 1 Col 2 Col 3

Row 0 A[0][0] A[0][1] A[0][2] A[0][3]

Row 1 A[1][0] A[1][1] A[1][2] A[1][3]

Row 2 A[2][0] A[2][1] A[2][2] A[2][3]

W02-Review of C++
39

2D Arrays

char A[4][3]; A[0]


{ A[0][0]
A[0][1]
A[0][2]

Row Major:
• A is an array of size 4.
A[1]
{ A[1][0]
A[1][1]
A[1][2]

• Each element of A is A[2]


{ A[2][0]
A[2][1]
A[2][2]

{
an array of 3 chars
A[3][0]
A[3] A[3][1]
A[3][2]

W02-Review of C++
40

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 20
12/02/2016

2D Array Example
const int r = 2;
const int c = 3;

void fillArray(int A[][c])


{ for (int i=0;i<r;i++)
for (int j=0;j<c;j++)
A[i][j] = i+j;
}

Draw memory contents of array A.


W02-Review of C++
41

2D Array Example
const int NumStudents = 10;
const int NumHW = 3;
double grades[NumStudents][NumHW];

for (int i=0;i<NumStudents;i++) {


for (int j=0;j<NumHW;j++) {
cout << “Enter HW “ << j <<
“ Grade for student number “ << i << endl;
cin >> grades[i][j];
}
}
W02-Review of C++
42

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 21
12/02/2016

2D Array Example

double studentAverage (double g[][NumHW], int stu)


{
double sum = 0.0;
for (int i=0; i<NumHW; i++)
sum += g[stu][i];
return(sum/NumHW);
}

W02-Review of C++
43

Using the studentAverage

for (int i=0; i<NumStudents; i++)


cout << “Student #” << i << “ has average “
<< studentAverage(grades, i) << endl;

W02-Review of C++
44

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 22
12/02/2016

Spring 2016
W02
Review of C++: Pointers

Declaration
Derefrencing Pointers
Pointers and Arrays
Pointer Arithmetic

45

Pointers
MEMORY
Address
A pointer is a variable that holds
0 the address
of another variable. 1
2
3
num
int num; 4 123
5
int *x;
...

...

num = 123; 81345


x 81346 4
x = &num; 81347

W02-Review of C++
46

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 23
12/02/2016

Pointer Variables

int *x; x some int

int **y;
y some *int some int

double *z;
z some double

W02-Review of C++
47

Dereferencing a Pointer

& is reference operator


* is dereference operator

A pointer must have a value before you can dereference it (follow


the pointer).

int *x; int num;


*x=3; int *x;
x = &num;
*x=3;

W02-Review of C++
48

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 24
12/02/2016

Pointer Example
int main ()
{
int firstvalue, secondvalue;
int * mypointer;

mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}

W02-Review of C++
49

Pointers and Arrays

 An array name is basically a const pointer.

 We can use the [] operator with a pointer.

int *x;
int a[10]; x is “the address of a[2] ”
x = &a[2];

W02-Review of C++
50

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 25
12/02/2016

Pointer Arithmetic

 Integer math operations can be used with


pointers.
 If you increment a pointer, it will be increased by
the size of whatever it points to.
int a[5];
int *ptr = a; *(ptr+2)
*(ptr+4)
*ptr

a[0] a[1] a[2] a[3] a[4]

W02-Review of C++
51

Example
int main ()
{
int numbers[5];
int* p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
return 0;
}
W02-Review of C++
52

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 26
12/02/2016

Printing an Array
void printArray (int A[], int len) {
for (int i=0;i<len;i++)
cout << "[" << i << "] = "
<< A[i] << endl;
}

void printArray (int *A, int len) {


for (int i=0;i<len;i++)
cout << "[" << i << "] = "
<< *A++ << endl;
}

W02-Review of C++
53

Passing Pointers as Parameters

void swap(int *x, int *y)


{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}

W02-Review of C++
54

Object Oriented Programming- Spring 2016


Instructor: Saima Jawad 27

You might also like