-2

I was practicing some sample in C++ I found a program where the code is given below:

unsigned int num;
int c = 0;
cin >> num;
for (; num; num <<= 1)
{
    if (num & 1)
    {
        c++;
    }
}
cout << "c : " << c << endl;

So I have following questions in mind:

  1. In this for loop condition, the second parameter is num — what is the significance keeping it as num; why not any condition like num<29 or may be some other value?

  2. Whereas the third parameter is z=num <<= 1, here I had kept z to do some debugging to know the value obtained on this condition, but I found that it just doubles when the operator is >>= and halves when it is <<=. Why this behavior?

  3. In the if condition we have if (int y=num & 1). I am not able to understand what it does with & 1?

I tried to understand it by debugging but I want to know clear explanation of these three questions so that's why I wanted to ask experts.

ajpr
  • 113
  • 1
  • 12
  • 5
    c/c++ is not a language – yizzlez Jul 31 '15 at 03:13
  • This is no C code. And - as @awesomeyi already stated - there is no language C/C++. – too honest for this site Jul 31 '15 at 03:15
  • Please get a C or C++ book. These are very basic operations you have to understand. And there is much more interesting stuff in books – too honest for this site Jul 31 '15 at 03:17
  • 2
    (1) The test `if (num)` is equivalent to `if (num != 0)`. (2) I think you have your observations back-to-front. `num >>= 1` will divide by 2; `num <<= 1` will multiply by 2. (3) The `y & 1` selects the least significant bit of `y`. Infelicity: You don't show the declaration of `z`, and you don't use the value of either `y` or `z`. Infelicity: because the code shown is left shifting num, the maximum value in `c` will be `1` (if the entered number is odd); otherwise, it is zero. That's because the left shift always inserts a zero in the least significant bit. – Jonathan Leffler Jul 31 '15 at 03:45

2 Answers2

6

For third,& is a bitwise AND operator. Doing if (int y=num & 1) checks if the last bit (least significant bit) of the number is set. If it is set, the number is odd, and if it is not set, it is even. However, y is trash here, if (num & 1) is enough for the checking.

2
  1. Since num is an unsigned int, the condition num in the for loop refers to it being true, or anything greater than 0. So the loop runs until num becomes 0 or less.

  2. << is known as the left-shift operator, while >> is the right-shift operator. I'll better leave it for you to understand how they work. Read the answers here to understand them better. Note: z is unused

  3. & is the bitwise AND operator. Note: y is unused too.

Community
  • 1
  • 1
CinCout
  • 9,486
  • 12
  • 49
  • 67