Question

Given the pseudo code below, what will be the output of the program, when the two parameters x and y are passed by value, and when they are passed by reference?

int x = 1;
int y = 1; 
int count = 0;
while count < 3{
addnumbers(x, y);
println (x);
count++;
}

addnumbers(int x, int y){
x = x + y;
println (x);
}
Was it helpful?

Solution

Pass by Value: In pass by value, when you pass a variable into a function, the function will use a copy of the variable, so the original is not affected.

2
1
2
1
2
1

Pass by Reference: In pass by reference, you pass the reference of the variable, so since both int x and int x inside the function reference the same thing, if you change one, the other one changes too.

2
2
3
3
4
4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top