Homework 5: Due  March 7, 2011


Bindings and scope

Textbook Chap 3 exercises: 3.6, 3.11 (in cases where multiple declarations occur, indicate which declaration is referenced), 3.14

Expressions

Textbook Chap 6 exercises: 6.12

A. Consider the following C++ program:

int func(int &i) {
   i = i + 5;
   return 4;
}

void main() {
   int x = 3;
   x = x + func(x);
}

Note that &i means that the parameter is using pass-by-reference, i.e. the address of the actual argument is passed to the function (rather than the value of the argument as is done in Java).

Trace execution of the main method and indicate the value of x under the condition that the expression on the right side of the second assignment statemen is evaluated:

1)  left to right
2) right to left

B. Consider the following Java code segment for doing a linear search of an array:

int i = 0;
while (i < arr.length && arr[i] != target) {
   i++;
}

1) After the loop terminates,  how would you determine whether target was found?

2) Rewrite this code segment to eliminate the statement in the body of the loop. How would this affect the answer to part 1)?

3) This algorithm takes advantage of short-circuiting. Re-write the algorithm to work in a language that does not does not have short-circuiting of boolean expressions so that it is equivalent to the code segment shown above (consider using a boolean variable).