Overview
How should we submit HW2?
Same as last time. Share github repo. Send a note to the grader (csc207-01-grader@grinnell.edu). The grader’s account is
csc207-grader
on GitHub. (At least I hope it is.)
Alternately, attach the files.
Wednesday’s labs were about ways to find/deal with incorrect code.
c2f
issues
sum
issues
Integer.MAX_VALUE
in Java, INT_MAX
in C), strange things
happen. It’s a consequence of how integers are stored in Java (and
C), which is two’s complement.What’s wrong with the following?
// Compute the average of two non-negative integers, rounding down
int average(int a, int b) {
return (a+b)/2;
}
a+(b-a)/2
expt
issues
Rather than testing “2^2 is 4”, “2^5 is 32”, “2^10 is 1024”, “3^5 = 243”, test x^0, x^1, x^2, x^3, … x^? using a for loop
for (int x = 1, x < 10; x++) {
int result = 1;
for (int i = 0; i < n; i++) {
assertEquals(result, expt(x,i));
result = result*x;
}
} // for
Other issues
Claim: Drawing pictures helps us understand code. For example, it’s much easier to write a linked-list implementation if you draw the pairs.
We’re going to draw pictures of the state of your Java programs.
Pictures will have two (or three) parts
Stack: Contains the local variables in each procedure. They are either primtive values (ints, etc.) or references to the objects and arrays we build.
When you call a method, an implicit this
variable gets added
to the stack, pointing to the corresponding object.
Heap: Contains the objects we build throughout the program.
What are “pass by value” and “pass by reference”?
In “pass by value”, you put the value of each actual parameter into the slot on the stack for the formal.
In “pass by reference”, you put the address of each actual parameter into the slot on the stack for the formal.
int i;
void f(int x) { ... }
...
f(i);
Pass-by-value
Stack
+----------+
x | 5 |
+----------+
i | 5 |
+----------+
Pass-by-reference
Stack
+----------+
x | &i |
+----------+
i | 5 |
+----------+