PDA

View Full Version : Need to understand this code


IT_helper
Apr 13, 2007, 07:55 AM
If MyClass includes the following declaration for Message:
public int Message(int m, int n)
{
n = n - 2;
return n - m;
}

and the following sequence of instructions is executed:
MyClass my = new MyClass();
int x = 3;
int y = 7;
x = y + my.Message(x, y - 1);
y = x + my.Message(y, x + 1);

What are the final values for x and y?
a) x is 8 and y is 8
b) x is 10 and y is 5
c) x is 10 and y is 7
d) x is 12 and y is 7

Can someone explain to me that code bit by bit please..? :( :confused:

Zeddicus88
Apr 23, 2007, 07:21 PM
If MyClass includes the following declaration for Message:
public int Message(int m, int n)
{
n = n - 2;
return n - m;
}

and the following sequence of instructions is executed:
MyClass my = new MyClass();
int x = 3;
int y = 7;
x = y + my.Message(x, y - 1);
y = x + my.Message(y, x + 1);

What are the final values for x and y?
a) x is 8 and y is 8
b) x is 10 and y is 5
c) x is 10 and y is 7
d) x is 12 and y is 7

Can someone explain to me that code bit by bit please.....???????????:( :confused:

OK here we go...

MyClass my = new MyClass();
This creates an object of the type MyClass using the default constructor.

int x = 3;
creates a primitive integer variable with the name "x" and initializes it value a 3.

int y = 7;
the same as "x" only the name is "y" and the value is 7.

here is where it gets tricky

x = y + my.Message(x, y - 1);
here you are reassigning the variable "x" to the current value of "y" plus the result of the "my.Message(x,y-1)" method call.
Message() takes the current value of "x" and assigns it to the local variable "m" in the parameter list of the method call and the value of y-1 to the local variable "n" also in the parameter list of the method. The following calculations occur: n is reassigned to its current value minus 2, then the result of the calculation n - m is returned.
we are now back to the original line of the program "x = y + my.Message(x,y-1);" only now we have a result for "my.Message(x,y-1)." we now add the current value of "y" (which did not change in the entire process) to the result of the method call and then giving the final result to the variable "x".

the next line follows a similar process. Here is the same code with all the variable replaced with there respective values.

MyClass my = new MyClass();
int x = 3;
int y = 7;
x = 7 + my.Message(3,7 - 1);

here we go to the method Message() with its given parameters

public int Message(3,6)
{
n = 6 - 2;
return 4 - 3;
}

so...
x = 7 + 1;
x is now 8.

y = 8 + my.Message(7, 8 + 1); note: y's value is still 7.

here we go again to the method Message() with its given parameters

public int Message(7,9)
{
n = 9 - 2;
return 7 - 7;
}

so...
y = 8 + 0;
y is now 8.
and your answer is "a) x is 8 and y is 8"

hope this helps a little