in Algorithms retagged by
11,301 views
18 votes
18 votes

Consider the following C functions.

int tob (int b, int* arr) {
    int i;
    for (i = 0; b>0; i++)  {
        if (b%2)  arr [i] = 1;
        else      arr[i] = 0;
        b = b/2;
    }
    return (i);
}

 

 

int pp(int a, int b)  {
    int  arr[20];
    int i, tot = 1, ex, len;
    ex = a;
    len = tob(b, arr);
    for (i=0; i<len ; i++) {
         if (arr[i] ==1)
             tot = tot * ex;
         ex= ex*ex;
    }
return (tot) ;
}

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

in Algorithms retagged by
by
11.3k views

4 Answers

18 votes
18 votes
Best answer

Answer $: 81$

$pp(3,4)$

  • $a=3, b=4 , \text{tot} = 1;$

len = tob(4, array) will return 3 with array set as $001$ as array is updated only once when  b%2 != 0). The for loop actually iterates $3$ times for $b = 4, b = 2$ and $b=1,$ and only when $b=1,$ arr[i] is updated.

Now pp will run for loop 3 times:

  1. $\text{arr}[0] = 0.$ So, $\text{ex} = 3\ast 3 = 9$
  2. $\text{arr}[1] = 0.$ So, $\text{ex} = 9\ast 9 = 81$
  3. $\text{arr}[1] = 1.$ So, $\text{tot} = 1\ast 81 = 81$
edited by

3 Comments

how Ara will become 001 it should  be 110  and why loop will run 3 time we got i = 2 they use len as varible not strlen function ? so i have two questions could you please explain  me ?

4%2 = 0  SO  a[0]=1  (i=0)

2%2=0 SO a[1]=1   (i=1)

1%2 != 0 so a[2]=0  (i=2)

so array i =2

there is len not strlen(function ) so how i =3?
1
1
Why i=3 only?.... i should go to upto last index of the array so I'm getting i=19
0
0

 

in tob() : initially i=0;

if(4%2) ---→ if(0) so, it execute else statement… a[0] = 0  then b=2, i =1;

if(2%2) ---→ if(0) so, it execute else statement… a[1] = 0  then b=1, i=2;

if(1%2) ---→ if(1) so, it execute if statement….. a[2] = 1 then b=0, i=3;

and for loop break and return(i=3) to the calling function…

i.e, len = 3;

 

 

1
1
4 votes
4 votes

THIS ILLUSTRATION MAY HELP😀

3 votes
3 votes
Answer: 81

4 Comments

@Bhupendra i will be 3 after the last iteration.
0
0
rt.. !! thanks
0
0
same i also got 27
0
0
0 votes
0 votes
Answer:

Related questions