Download presentation
Presentation is loading. Please wait.
1
CIS 101: Computer Programming and Problem Solving Lecture 9 Usman Roshan Department of Computer Science NJIT
2
C++ functions Function definition: (, …, ); For example, int myadd(int x, int y)l int max(int x, int y);
3
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()
4
myadd function First define function
5
Same function with different parameters--overloading
6
Passing arrays as arguments Define function before main
7
Program output
8
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 memory location of the variable x y x 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.
9
Pointers and references
10
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.
11
Pointers and reference int *x; x = new int[1]; *x = 2; Memory x 50 2 *x
12
Pointers
13
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.
14
Dynamic arrays int *x; x = new int(3); x[0] = 2; x[2] = 4; x[3] = 6; Memory x 50 2 x[0] 46 x[1] x[2]
15
Dynamic arrays
16
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;
17
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.
18
Program output
19
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.
20
Program output
21
Two dimensional arrays 2D arrays are defined as int A[10][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.
22
Lab problems 1.Power function to compute x^y 2.Swap function to interchange two numbers 3.Copy array function 4.Problems from midterm
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.