Why does this program just print odds to the screen? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why does this program just print odds to the screen?

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

2nd Nov 2018, 3:03 AM
School Dog
1 Answer
+ 7
Your if statement is a faster odd test than: if(i%2==1) It does a bitwise and of the number i and 1. This results in 0 for evens or 1 for odds as both bits must be 1 to result in a 1. Any non-zero value is true so odds get printed.
2nd Nov 2018, 3:49 AM
John Wells
John Wells - avatar