Knowee
Questions
Features
Study Tools

What will be the output of the following code?int num = 2;int count=0;while(num!= 0){if ( num & 01)count ++;num >>=1;}cout<< count;return 0;

Question

What will be the output of the following code?int num = 2;int count=0;while(num!= 0){if ( num & 01)count ++;num >>=1;}cout<< count;return 0;

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the code will be 1.

Here's the step by step explanation:

  1. The variable num is initialized with the value 2 and count is initialized with 0.
  2. The while loop will continue as long as num is not equal to 0.
  3. Inside the loop, the if statement checks if the bitwise AND operation between num and 1 is true. In binary, 2 is represented as 10. So, the bitwise AND operation between 2 (10 in binary) and 1 (01 in binary) is 0. Therefore, count is not incremented.
  4. Then, the right shift operator >>= shifts the bits of num to the right by one place. The binary representation of 2 (10) becomes 1 (01).
  5. The loop continues. Now, the bitwise AND operation between num (which is now 1) and 1 is 1. Therefore, count is incremented by 1.
  6. num is again shifted to the right by one place. Now, num becomes 0 and the loop ends.
  7. Finally, count is printed, which is 1.

This problem has been solved

Similar Questions

What will the result of num1 variable after execution of the following statements? int j = 1, num1 = 4; while (++j <= 10) { num1++; } write the output of the code

What will be the output of the following code?int i = 1;while(i<10){  if (i % 2 == 0)     cout << i << “ ”; i++;}

What is the output of the programme below?public static void main(String[] args) {     int x = 0;     while (x < 10) {          if (x & 2 == 0) {               System.out.print(x + “ “);          }          x++;     }}

What is the output of the following code snippet?int i = 1;while (i <= 5) {    if (i % 2 == 0)        continue;    System.out.print(i + " ");    i++;}Question 13Answera.1 2 3 4 5b.The code will result in an infinite loop.c.1 3 5d.2 4

What will be the output of the following code ?public static void print(int n){ if(n < 0){ return; } if(n == 0){ System.out.println(n); return; } print(n--); System.out.print(n+" ");}public static void main(String[] args) { int num = 3; print(num);

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.