cis 101: computer programming and problem solving lecture 9 usman roshan department of computer...

22
CIS 101: Computer Programming and Problem Solving Lecture 9 Usman Roshan Department of Computer Science NJIT

Post on 20-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

CIS 101: Computer Programming and Problem Solving

Lecture 9Usman Roshan

Department of Computer Science

NJIT

C++ functions

Function definition:

<return value> <function_name> (<arg1_type> <arg1>, <arg2_type> <arg2>,…,<argn_type> <argn>);

For example, int myadd(int x, int y)lint max(int x, int y);

C++ functions

Compiler goes from top to bottom. So, either

(1) Declare function before main() and then define it anywhere in the file

(2) Or define it before main()

myadd function

First define function

Same function with different parameters--overloading

Passing arrays as arguments

Define function before main

Program output

Pointers and reference

int x=2; int *y;

y = &x;

2 2

Memory

Memory is organized into cells. Let’s say x is in cell number 100

100

Returns memorylocation of thevariable

x

yx

y is a pointer to an integer. We set it to point to x which means it will now containthe memory location of x.

Pointers and references

Dynamic memory allocation---creating and deleting arrays of arbitrary size

int *x;

x = new int[1];

We first create an array pointer and then

create space in memory for one integer it

can point to.

Pointers and reference

int *x;

x = new int[1];

*x = 2;

Memory

x

50 2

*x

Pointers

Output of pointer programx is a pointer to a location in memory which is why it shows up in HEX

The memory location x points to contains 2.

Dynamic arrays

int *x;

x = new int(3);

x[0] = 2;

x[2] = 4;

x[3] = 6;

Memory

x

50 2

x[0]

4 6

x[1] x[2]

Dynamic arrays

Dynamic arrays

• Memory defined using new must be cleared up using delete. Otherwise your program may use up ALL the memory.

int *x = new int[10];

.

.

delete x;

Passing variables by value

A new variable is createdthat contains a copy of x

This means the value in the original variableis unchanged.

Program output

Passing variables by reference

& means we are receiving areference to the original variableand it can be modified.

Now the value in the original variablex can be modified.

Program output

Two dimensional arrays

2D arrays are defined asint A[10][10];This allocates space for a 2-D array of dimension 10 times 10, with un-initializedvalues.You can also doint *a[10];This creates an array of 10 integer pointers forwhich space has to be allocated using new.

Lab problems

1. Power function to compute x^y

2. Swap function to interchange two numbers

3. Copy array function

4. Problems from midterm