344 views
0 votes
0 votes
void foo(int n)

{

  while (n! = 0)

       {

         if  (!(n & 1))

          printf(“*”);

          n = n >> 1 ;

     }

}

 

The number of times printf(“*”) is executed, when the value 2 raised to power 24 is passed to the function foo() is ?

2 Answers

1 votes
1 votes
24 is the answer

Last statement is right shift operator which means divide by 2 and the condition is bitwise AND with 1 which keep on resulting zero (!0=1 condition true) till the number is greater than 1. At 1 (1&1=1 condition becomes false) you can run the code for small example like 2^3 and printf will be executed 3 times.
1 votes
1 votes

Ans is 24.

First understand following operation on bits

n & 1 returns true when last bit of n is 1 or say when s is odd. Therefore !(n&1) returns true when n is even or last bit of n is 0.

n= n >>1, shifts the bits of n rightwards by 1 position. It is equivalent to n = n/2

Now $2^{24}$ means 1 followed by 24 zeros in binary.

As loop executes n will keep shifting rightwards..

$2^{24}$ -> $2^{23}$ -> $2^{22}$ ->... -> $2^{1}$

Therefore 24 times.

Related questions

0 votes
0 votes
1 answer
1
0 votes
0 votes
1 answer
2
tishhaagrawal asked Dec 16, 2023
352 views
Below is my approach to solving this question, can anyone please explain if I am doing it the right way?Let X = #free slotssince, m =7 and n = 3So, $4 \leqslant x\leqsla...
0 votes
0 votes
0 answers
3
Dadu asked Dec 7, 2023
211 views
Please solve I am unable to understand the solution given by made easy