Title: CIS 101: Computer Programming and Problem Solving Lecture 9
1CIS 101 Computer Programming and Problem
SolvingLecture 9
- Usman Roshan
- Department of Computer Science
- NJIT
2C functions
- Function definition
- ltreturn valuegt ltfunction_namegt (
- ltarg1_typegt ltarg1gt,
- ltarg2_typegt ltarg2gt,
- ,
- ltargn_typegt ltargngt)
- For example,
- int myadd(int x, int y)l
- int max(int x, int y)
3C functions
- Compiler goes from top to bottom. So, either
- Declare function before main() and then define it
anywhere in the file - Or define it before main()
4myadd function
First define function
5Same function with different parameters--overloadi
ng
6Passing arrays as arguments
Define function before main
7Program output
8Pointers and reference
Returns memory location of the variable
Memory
x
100
2
2
y
x
Memory is organized into cells. Lets 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.
9Pointers and references
10Dynamic memory allocation---creating and deleting
arrays of arbitrary size
- int x
- x new int1
- We first create an array pointer and then
- create space in memory for one integer it
- can point to.
11Pointers and reference
Memory
50
2
x
x
12Pointers
13Output 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.
14Dynamic arrays
- int x
- x new int(3)
- x0 2
- x2 4
- x3 6
Memory
50
2
4
6
x0
x
x1 x2
15Dynamic arrays
16Dynamic arrays
- Memory defined using new must be cleared up using
delete. Otherwise your program may use up ALL the
memory. - int x new int10
- .
- .
- delete x
17Passing variables by value
A new variable is created that contains a copy of
x
This means the value in the original variable is
unchanged.
18Program output
19Passing 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.
20Program output
21Two dimensional arrays
- 2D arrays are defined as
- int A1010
- This allocates space for a 2-D array of
- dimension 10 times 10, with un-initialized
- values.
- You can also do
- int a10
- This creates an array of 10 integer pointers for
- which space has to be allocated using new.
22Lab problems
- Power function to compute xy
- Swap function to interchange two numbers
- Copy array function
- Problems from midterm