Chapter 11 Exercise Set 1: CPE Practice¶
Bitwise Operators¶
C++ has the following operators that work at the level of bits:
Bitwise AND (
&
)Bitwise OR (
|
)Bitwise XOR (
^
)Bitwise NOT (
~
)Left Shift (
<<
)Right Shift (
>>
)
What is the output of the following program?
#include <iostream> using namespace std; int main() { int a[6]; for (int i = 0; i < 6; i++) a[i] = 2 * i + 4; cout << a[4] / a[1] << endl; return 0; }
1
2
4
8
What is the output of the following program?
#include <iostream> using namespace std; int main() { int a = 2, b = 3; if (a > b && b > a) a++; if (a > b || b > a) b++; if (a | b) a++; if (a & b) b++; cout << a * b << endl; return 0; }
6
9
8
12
What is the output of the following program?
#include <iostream> using namespace std; int main() { int a = 1, b = 2, c; a = a << b; b = b << a; c = b >> a; cout << c << endl; return 0; }
2
4
6
8
What is the output of the following program?
#include <iostream> using namespace std; int main() { float a[3][3] = {{.1, 1., 10.}, {10., .1, 1.}, {.1, 10., 1.}}; float f = 10.; for (int i = 0; i < 3; i++) f *= a[i][i]; cout << f << endl; return 0; }
100
0.1
0.01
10
What is the output of the following program?
#include <iostream> using namespace std; int main() { int nums[4] = {16, 8, 4, 2}; int *p1 = nums + 2, *p2 = p1 - 1; p1++; cout << *p1 << ' ' << *p2 << ' ' << p1 - p2 << ' '; cout << *p1 + nums[p1 - p2] << endl; return 0; }