Quiz 2 Solutions

1 October 2014

You have up to 20 minutes. Please write your answers on this page, and your name at the top. You may not use the computer, notes, or books.

  1. The following program uses a variety of arithmetic operators and mathematical functions. What does it output? You can write each line of output to the right of the corresponding endl.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    cout << 9 / 2            << endl; // _______
    cout << 7 / 2.0          << endl; // _______
    cout << 17 % 2           << endl; // _______
    cout << 31 % 7           << endl; // _______
    cout << pow(3,3)         << endl; // _______
    cout << sqrt(25)         << endl; // _______
    cout << floor(9.8)       << endl; // _______
    cout << sqrt(pow(2,4))+1 << endl; // _______
    return 0;
}

4
3.5
1
3
27
5
9
5

  1. Suppose that we have a main program containing this declaration:

      string courseTitle;

    Briefly explain the difference between these two operations:

      cin >> courseTitle;         // (a)
      getline(cin, courseTitle);  // (b)

The first one (a) reads only one word from the input, and leaves the ‘cursor’ just before the first space or newline. The second one (b) reads an entire line up to the user pressing enter.

  1. The following program does some arithmetic on char types. What does it output?
#include <iostream>
using namespace std;
int main()
{
    char one = 'I';
    char fiv = 'V';
    char x   = one + 4;
    char y   = fiv + 2;
    cout << x << x << y << one << fiv << endl;
    return 0;
}

MMXIV

  1. The program below uses conditional statements (specifically, an if-else chain). Given the values of x and y as inputs, what does the program output?

    • x = 6; y = 3; Output: A
    • x = 7; y = 7; Output: B
    • x = 5; y = 5; Output: A
    • x = 7; y = 10; Output: C
#include <iostream>
using namespace std;
int main()
{
    int x, y;
    cout << "Enter two integers: ";
    cin >> x >> y;
    if(x < 7)
    {
        cout << "A";
    }
    else if(y < 9)
    {
        cout << "B";
    }
    else
    {
        cout << "C";
    }
    return 0;
}