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 (>>)

  1. 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. 1

    2. 2

    3. 4

    4. 8

  2. 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;
    }
    
    1. 6

    2. 9

    3. 8

    4. 12

  3. 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;
    }
    
    1. 2

    2. 4

    3. 6

    4. 8

  4. 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;
    }
    
    1. 100

    2. 0.1

    3. 0.01

    4. 10

  5. 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;
    }