Computer Sciences > Gate 2016 Set-1 > C code
What will be the output of the following pseudo-code when parameters are passed by reference and dynamic scoping is assumed?

a=3;
void n(x) {x = x * a; print(x);}
void m(y) {a = 1; a = y - a; n(a); print(a);}
void main() {m(a);}

A
6, 2
B
6, 6
C
4, 2
D
4, 4

Correct : C

Given:
- Initial global variable: a = 3
- Parameter passing: Call by reference
- Scoping rule: Dynamic scoping
- Functions:
void n(x) { x = x * a; print(x); }
void m(y) { a = 1; a = y - a; n(a); print(a); }
void main() { m(a); }
To find:
- The output of the pseudo-code.
Solution:
Okay, let's trace the execution step by step starting from main().
First, main() calls m(a) with the global variable a (which is 3) passed by reference to parameter y.
So, y inside m is an alias/reference to the global variable a (value = 3).
Now entering function m(y):
The first statement is a = 1, which defines a local variable a in m initialized to 1.
Next, evaluating a = y - a:
Since y refers to global a = 3 and local a = 1, we get:
a = 3 - 1 = 2.
So, local a in m now has the value 2.
Now, m calls n(a), passing its local variable a by reference to x.
So, x inside n is an alias/reference to m's local variable a.
Now entering function n(x):
Because dynamic scoping is used, any free variable is resolved by looking back up the calling sequence (call stack).
The caller of n is m, so the identifier a resolves to the local variable a of m, which has the value 2.
The parameter x is also referencing that very same local variable a of m, so x = 2.
Now executing the statement x = x × a:
x = 2 × 2 = 4.
Because x is passed by reference, updating x directly updates the local variable a in m to 4.
Now, printing x gives:
print(x) → 4.
Function n finishes and control returns to m.
Back in m, the next statement is print(a):
Since a was modified by n via reference parameter x, the value of a is now 4.
print(a) → 4.
Therefore, the outputs are 4 and 4.
Answer:
D) 4, 4

Similar Questions

Consider the following program in C language: #include <stdio.h> main() {     int i;     int *pi = &i;     scanf("%d",...
#16 MCQ
Consider the following two C code segments. Y and X are one and two dimensional arrays of size n and n × n respectively, where 2 ≤ n ≤ 10. Assume that in both c...
#25 MCQ
Consider the following C program segment. #include<stdio.h> int main( ) {     char s1[7] = "1234", *p;     p = s1 + 2;    ...
#37 MCQ

Related Topics

pseudo code question GATE computer science 2016 by reference parameters dynamic scoping pseudo code execution function call main n(x) void function m(y) void function print x y GATE 2016 Set-1 variable scope

Unique Visitor Count

Total Unique Visitors

Loading......