0

Pls 🙏 how does this code works

#include <iostream> using namespace std; int main() { for (int i =0;i<40;i++){ if (i&5){cout<<i<<" ";} } return 0; }

24th Jun 2022, 6:30 AM
Ayomo Joshua Odunayo
Ayomo Joshua Odunayo - avatar
5 Réponses
+ 2
When i=0 if condition output is zero so condition is false so no output when i=0. When i= 1 if condition statement output is 1 which is true so output is 1
24th Jun 2022, 9:26 AM
Mihir Lalwani
Mihir Lalwani - avatar
+ 1
code print only when if statement have greater than condition when i= 0 (0000)&(0101) which will result as (0000)=0 when i=1 (0001)&(0101) which will result as (0001)=1 when i=2 (0010)&(0101) which will result as (0000)= 0 when i=3 (0011)&(0101) which will result as (0001)=1 when i=4 (0100)&(0101) which will result as (0100)=4 & (bitwise and operator work on bits 1&0 = 0 1&1 = 1 0&1 = 0 0&0 = 0 )
24th Jun 2022, 8:32 AM
Mihir Lalwani
Mihir Lalwani - avatar
+ 1
So what will be the output of the code?
24th Jun 2022, 8:55 AM
Ayomo Joshua Odunayo
Ayomo Joshua Odunayo - avatar
+ 1
the value of i for which the if condition true is output
24th Jun 2022, 9:24 AM
Mihir Lalwani
Mihir Lalwani - avatar
0
Ayomo Joshua Odunayo to see the output you may run it yourself in the Code Playground. It prints only numbers that have bit0 or bit2 set to 1. The value 5 (101 in binary) is used as a bit mask that allows bit0 and bit2 but blocks all other bits. If either bit is 1, then the conditional is true (non-zero); otherwise it is false (0). Stated another way, the output would show odd numbers (bit0), and odd multiples of four (bit2) and their next higher even number.
24th Jun 2022, 4:37 PM
Brian
Brian - avatar