Practice with if/else

7 October 2013

The program on this page uses nested conditional statements. Given the values of x and y as inputs, what does the program output?

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

This is a similar problem, but the program on this page uses a switch statement. Given the value of k as input, what does the program output?

  • k = 2; Output:
  • k = 3; Output:
  • k = 4; Output:
  • k = 5; Output:
  • k = 6; Output:
#include <iostream>
using namespace std;
int main()
{
    int k;
    cout << "Enter an integer: ";
    cin >> k;
    switch(k) {
    case 4:
        cout << "A";
        break;
    case 3:
        cout << "B";
        break;
    case 5:
        cout << "C";
    default:
        cout << "D";
        if(k >= 6) {
            cout << "E";
        }
    }
    cout << "F";
    return 0;
}