Worksheet: Switch Statements

1. Given the following switch statement:

    cout << "enter the grade:  ";
    cin >> grade;
    switch (grade)
    {
	case 'A':
	case 'B':
            cout << "good work" << endl;
            break;
	case 'C':
            cout << "average work" << endl;
            break;
	case 'D':
            cout << "just passing" << endl;
            break;
	case 'F':
            cout << "poor work" << endl;
            failing++;
            break;
    }

What would be printed if the grade were:
   A. A
   B. D
   C. b


2. Modify the switch statement in question 1 so that it prints an
   error message if an invalid grade is entered.


3. Modify the switch statement in question 1 so that it works for grades
   entered as uppercase or lowercase letters.


4. A. Write the equivalent if/else statements for the program segment
      in Question # 1.
   B. If you were guaranteed that only VALID grades would be entered
      by the user, could the if/else statement be written any
      differently? If so, how?


5. Show the output of the following:

    int1 = 4;
    switch (int1)
    {
        case 1:
            cout << 4;
            break;
        case 2:
            cout << 1;
            break;
        case 3:
            cout << 7;
            break;
        case 4:
            cout << 9;
            break;
        case 5:
            cout << 6;
            break;
    }


6. Show the output of the following:

    int1 = 4;
    switch (int1)
    {
       case 1:
           cout << 4;
           break;
       case 2:
           cout << 1;
           break;
       case 3:
           cout << 7;
           break;
       case 2:
           cout << 9;
           break;
       case 5:
           cout << 6;
           break;
    }


7. Show the output of the following:

    int1 = 4;
    switch (int1)
    {
       case 1:
           cout << 4;
           break;
       case 2:
           cout << 1;
           break;
       case 3:
           cout << 7;
           break;
       case 4:
           cout << 9;
       case 5:
           cout << 6;
    }


8. An electronics store is having a sale. Items from the audio department
   (dept code 310) are 10% off. Items from the video department (dept
   code 438) are 12% off. Items from the computer department (dept
   code 284) are 8% off, and items from the communications department
   (dept code 652) are 15% off. Items from other departments are 5%
   off. Write the statements to read in the regular price of an item and
   the dept code, and calculate the sale price. Print the regular price
   and the sale price. Use a nested if statement.


9. Rewrite your code from problem 7 using a switch statement.


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002