Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

GATE | GATE-CS-2016 (Set 2) | Question 45

  • Difficulty Level : Basic
  • Last Updated : 12 Aug, 2021

The following function computes XY for positive integers X and Y.

Attention reader! Don’t stop learning now.  Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.

Learn all GATE CS concepts with Free Live Classes on our youtube channel.

int exp(int X, int Y)
    int res = 1, a = X, b = Y;
    while ( b != 0 )
        if ( b%2 == 0)
            a = a*a;
            b = b/2;
            res = res*a;
            b = b-1;
    return res;

Which one of the following conditions is TRUE before every iteration of the loop

(A) A
(B) B
(C) C
(D) D

Answer: (C)

We can solve this question taking any two values for X and Y.
Suppose X= 2 and Y= 5, now this code will calculate
Looking at each iteration separately
Before iteration 1 – X=2 Y= 5 a=2 , b=5, res=1
Iteration 1 – since b%2 !=0 we go to else part
Therefore after iteration 1, X=2, Y=5, a=2, b=4, res=2
Iteration 2 – since b%2=0 we go to if part
Therefore after iteration 2 , X=2, Y=5, a=4, b=2, res=2
Iteration 3 – since b%2=0 we go to if part
Therefore after iteration 3 , X=2, Y=5, a=16, b=1, res=2
Iteration 4 – since b%2!=0 we go to else part
Therefore after iteration 4 , X=2, Y=5, a=16, b=0, res=32
Now putting the values of X, Y , a, b, res in the equations given in options after each
iteration we can see only equation c is correct.

This solution is contributed by Parul sharma.

Another solution

In option C

Before Iteration 1: X^Y=64 res ∗ (a^b)=64
Before Iteration 2: X^Y=64 res ∗ (a^b)=64
Before Iteration 3: X^Y=64 res ∗ (a^b)=64 

Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!