Skip to content
Official PYQ · 2001

GATE CS 2001 Q2.19 — Programming in C

Explain with AI

Consider the following program

Program P2
    var n : int;
    
    procedure W(var x : int)
    begin
        x = x + 1;
        print x;
    end

    procedure D
    begin
        var n : int;
        n = 3;
        W(n);
    end

    begin    \\begin P2
        n=10;
        D;
    end

If the language has dynamic scooping and parameters are passed by reference, what will be printed by the program?

Choose one option
View worked solution

Answer: D

To find the output of the program, let's trace its execution step-by-step:

  1. Main Program Execution:
    • The global variable n is assigned the value 10.
    • Procedure D is called.
  2. Inside Procedure D:
    • A local variable n is declared, which shadows the global n.
    • This local n is assigned the value 3.
    • Procedure W(n) is called, passing the local variable n as an argument.
  3. Inside Procedure W:
    • Since parameters are passed by reference, the formal parameter x becomes an alias (reference) to the local variable n of procedure D.
    • The statement x = x + 1 increments the value of the referenced variable (local n of D) from 3 to 4.
    • The statement print x prints the current value of x, which is 4.

Note on Scoping: Dynamic scoping determines how non-local (free) variables are resolved by searching the activation stack. Since procedure W only accesses its local parameter x and does not use any non-local variables, the choice of dynamic scoping versus static scoping does not affect the output here.

Since the program prints 4, which is not present in options A, B, or C, the correct option is D.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions