Hello,
Could you explain me what this statement means? I am confused with k/=2 as iteration statement. for (int k = p; k > 0; k /= 2) Thanks

k/=2 is equivalent to k = k / 2;
so this expression looks like it should function once, halving the value of k and running the internal loop once.

Assuming that the int k is not negative.

I see. It's confusing having k=k/2 written that way.

But then why do you say it will function once? If we start from positive p and keep halving it, we would never reach a value <= 0, so it would go on forever, wouldn't it?

The end condition is reached on first iteration with a positive value.

As the value is int though rather than float and x/2 is the same as right shifting it, you will eventually get 0.

eg 9 is 101
9 /2 = 4.5 or in binary 010
9/4 = 2.25 is shown in ints as 2
and 9/8 is shown as 1
and therefore 9/16 is 000

Integer division will always be zero as "C" floors it.

Odd number: 5

5 / 2 = 2
2 / 2 = 1
1 / 2 = 0

Even number: 4

4 / 2 = 2
2 / 2 = 1
1 / 2 = 0

As you can see with this small (non legal C) program:

int main(){
  unsigned int x;
  scanf("%u", &x);

  while(x){
    printf("x = %d\n", x);
    x = x / 2;
  }
  
  printf("x = %d\n", x);
  
  return 0;
}

With output:

C:\Code>TMP
5
x = 5
x = 2
x = 1
x = 0

C:\Code>TMP
4
x = 4
x = 2
x = 1
x = 0

well, if k = 10 or 11 after 1st iteration it becomes 5 then 2 then 1 and then 0 to exit.

I guess stephen said that this halving occurs once every iteration

EDIT: Too late

This article has been dead for over six months. Start a new discussion instead.