Questions from an old test


What is the output from each of the code segments below? In addition, what is the output regardless of the values of the variables? See the inline comments; the first one is done for you. Your answers should be in terms of the possible range of values for the variables. Be specific and clear. Try to figure out the answers first, then click for answers.

  1. int x = 1, y = 0;

    if(x > y && y < 0)
        cout << "AAA\n";    // x is greater than y -AND- y is negative
    else
        cout << "BBB\n";    // x is less than or equal to y -OR- y is non-negative


  2. int x = 1, y = 0, z = -1;

    if(y >= x || z == -1)
        cout << "CCC\n";     // Under what conditions will CCC be displayed?
    else if(x > z)
        cout << "DDD\n";     // Under what conditions will DDD be displayed?


  3. int x = 1, y = 0, z = -1;

    if(x != y)
        if(y != z)
            x = 30;           // Under what conditions will x get 30?
        else
            x = 60;           // Under what conditions will x get 60?
    else
        x = 10;               // Under what conditions will x get 10?

    cout << "Answer: " << x << endl;


  4. int x = 1, y = -1;

    if(y)
        cout << "one\n";     // Under what conditions will one be displayed?
    else if(x)
        cout << "two\n";     // Under what conditions will two be displayed?
    else
        cout << "three\n";   // Under what conditions will three be displayed?
Click for answers.