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;
Solution
The output of the code will be 1.
Here's the step by step explanation:
- The variable
numis initialized with the value 2 andcountis initialized with 0. - The
whileloop will continue as long asnumis not equal to 0. - Inside the loop, the
ifstatement checks if the bitwise AND operation betweennumand 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,countis not incremented. - Then, the right shift operator
>>=shifts the bits ofnumto the right by one place. The binary representation of 2 (10) becomes 1 (01). - The loop continues. Now, the bitwise AND operation between
num(which is now 1) and 1 is 1. Therefore,countis incremented by 1. numis again shifted to the right by one place. Now,numbecomes 0 and the loop ends.- Finally,
countis printed, which is 1.
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);
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.