English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

void fn(int n)
{
while(n != 0)
{
n >>= 1;
//do something
}
return;
}

2007-03-06 16:06:41 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

if n<0
sign bit for n will be 1.
When you right shift n, this sign bit will be extended to 7th bit and still the sign bit remains in the 8th bit.

suppose n=11111111
when you right shift again its 11111111

supopse n=10111111
when you right shift it become 11011111
next right shift 11101111
11110111
11111011
11111011
11111101
11111110
11111111
and so on



So there is no chance of n being zero.


So its infinite loop

Do anybody disagree?
-
PC

2007-03-08 15:55:37 · answer #1 · answered by PC 4 · 0 0

The answer is machine dependent. When (n < 0) means n is some number which is not zero, and hence the shile loop will be executed for sure, atleast once. And it will be executed (log(MAX_INT_NUMBER + n)) times, where log is with base 2. MAX_INT_NUMBER is the maximum integer number you can have on your system. This depends on 16 bit, 32 bit or 64 bit int.
It is simple actually. When n > 0, the loop will be executed logn times. When n < 0, the loop will be executed depending what is the presentation of that number as negative number.
e.g for n = 5 the n in binary look like 00000101. The loop will be executed 3 times, and the value of n will be changed as
00000010, 00000001, and finally 000000000.
When n is -5, the binary presentation will be 11111110. Clearly the loop will be executed 8 times.

2007-03-07 02:24:57 · answer #2 · answered by manoj Ransing 3 · 0 0

Loop will be executed successfully. Because the condition is the value of the variable n is not equal to zero. But i don't know when will it stop.

2007-03-07 00:19:58 · answer #3 · answered by sridhar b 2 · 0 0

The while loop never executes!

2007-03-07 00:09:25 · answer #4 · answered by Anonymous · 1 0

fedest.com, questions and answers