Skip to main content

GATE CSE 2020Algorithms › Program & Function TracingVerified

GATE CSE 2020 PYQ: Consider the following C functions. int tob ( int b , int * arr ) { int i ; for ( i = 0 ; b > 0 ; i ++) { if…

Consider the following C functions.

  1. int tob (int b, int* arr) {
  2. int i;
  3. for (i = 0; b>0; i++)  {
  4. if (b%2)  arr [i] = 1;
  5.        else      arr[i] = 0;
  6.        b = b/2;
  7.   }
  8. return (i);
  9. }

 

 

  1. int pp(int a, int b)  {
  2. int  arr[20];
  3. int i, tot = 1, ex, len;
  4.     ex = a;
  5.     len = tob(b, arr);
  6.     for (i=0; i<len ; i++) {
  7.          if (arr[i] ==1)
  8.              tot = tot * ex;
  9.         ex= ex*ex;
  10.     }
  11. return (tot) ;
  12. }

The value returned by pp(3,4)pp(3,4) is _______.

    Answer

    81

    Approach

    Trace the two functions with a = 3 and b = 4. First, tob(4, arr) fills arr with the binary bits of 4 from least significant bit to most significant bit and returns the number of bits. Then pp(3,4) iterates over those bits; whenever arr[i] is 1, it multiplies tot by ex, and it squares ex after every iteration.

    The binary bits of 4 are stored as arr = [0,0,1] in LSB-first order, and the only set bit is at position 2. Since ex is squared after each iteration, it equals $3^(2^2) = 3^4 = 81$ at that position, so tot becomes 81.

    Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.