retagged by
1,095 views
5 votes
5 votes

Consider the function func shown below: 

int func(int num) 
{ 
   int count = 0; 
   while (num) 
    { 
     count++; 
     num>>= 1; 
    } 
   return (count); 
}

The value returned by func(-435) is:

  1. 6
  2. 9
  3. Will loop forever
  4. Depends on computer architecture
retagged by

2 Answers

1 votes
1 votes

Answer (c) correct, considering this reasoning

 

A good point to add here is

X>>1 is not the Logical right shift

X>>1 is arithmetic right shift(sign bit is preserved)   – @Shubhodeep

edited by
0 votes
0 votes

The value returned by the function func(-435) is option a. 6.

The function func(num) uses a while loop that continues to shift the bits of the number to the right using the bitwise right shift operator (>>=) and increments a count variable each time a 1 is encountered in the least significant bit. The loop stops when the number becomes zero. However, the function doesn't take into account the case of negative numbers, which are represented in two's complement notation. The leftmost bit represents the sign of the number (0 for positive, 1 for negative) and is not counted as part of the number of bits set to 1. So in the case of -435, when the function is called, it will count all the bits including the leftmost bit, which is 1, resulting in 6 bits set to 1 instead of 5.

Option b.9 is incorrect, as it is not the number of bits set to 1 in the binary representation of -435, option c. Will loop forever and d.Depends on computer architecture are not applicable to this scenario as the function will return the incorrect value on any computer architecture.

Related questions

27 votes
27 votes
5 answers
1
go_editor asked Sep 28, 2014
11,369 views
Consider the function func shown below: int func(int num) { int count = 0; while (num) { count++; num>>= 1; } return (count); }The value returned by func($435$) is ______...
11 votes
11 votes
4 answers
4