Problem Set
1. Suppose you want to write a method that prints a heading on a new output page with a page number that is 1 in the first activation and that increases by 1 with each subsequent activation. Can this be done without parameters in Java? Suggest a way to do that.
This can be done by using a static (or class) data member for the page number.
2. Consider the following program written in C syntax:
void swap (int a, int b) { int temp; temp = a; a = b; b = temp;
}
Void main() { int value = 1, list [5] = {2, 4, 6, 8, 10);
swap (value , list [0]);
swap (list[0], list[ 1]);
}
For each of the following parameter-passing methods , what are the values of variables value and list after the two calls to swap?
a) Passed by value
With pass by value, none of the actual arguments are changed, so the variables retain the values they were initialized with.
Both first and second call to swap: value = 1 list[5]={2,4,6,8,10} b) Passed by reference
With pass by reference, the arguments are changed. After the first call to swap, value == 2 and list[0] == 1. After the second call to swap, list[0] == 4 and list[1] == 1.
First call to swap: value = 2 list[5]={1,4,6,8,10} Second call to swap: value = 2 list[5]={4,1,6,8,10} c) Passed by value –result In this case, value-result has the same effect as reference.
3. Given the following program in C:
Void fun (int first, int second) {
first += first; second += second;
} void main () {
Int list[2] = { 3,5}; fun (list[0], list[1]);
}
For each of the following parameter passing methods, what the values of the list array after execution?
a. Passed by value copy going into the procedure
3,5
b. Passed by reference pass a pointer to the actual parameter, and indirect through the pointer
6,10
c. Passed by value-result copy going in, and again going out
6,10
NOTES: techniques used for argument passing: call by value call by result call by value-result call by reference