CIS 101 Computer Programming and Problem Solving Lecture
CIS 101: Computer Programming and Problem Solving Lecture 9 Usman Roshan Department of Computer Science NJIT
C++ functions Function definition: <return value> <function_name> ( <arg 1_type> <arg 1>, <arg 2_type> <arg 2>, …, <argn_type> <argn>); For example, int myadd(int x, int y)l int 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; Memory Returns memory location of the variable x 100 2 2 y x Memory is organized into cells. Let’s say x is in cell number 100 y is a pointer to an integer. We set it to point to x which means it will now contain the 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 50 x 2 *x
Pointers
Output of pointer program x 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 50 x 2 4 6 x[0] 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 created that contains a copy of x This means the value in the original variable is unchanged.
Program output
Passing variables by reference & means we are receiving a reference to the original variable and it can be modified. Now the value in the original variable x can be modified.
Program output
Two dimensional arrays 2 D arrays are defined as int A[10]; This allocates space for a 2 -D array of dimension 10 times 10, with un-initialized values. You can also do int *a[10]; This creates an array of 10 integer pointers for which 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
- Slides: 22