Notes for Oct 12

switch-ordinal.cpp

An example of using switch with fall-through to put ordinal suffixes on numbers in dates.

#include <iostream>
using namespace std;
int main()
{
    int day;
    cout << "Enter day of month: ";
    cin >> day;

    cout << "October " << day;
    switch(day)
    {
    case 1: case 21: case 31:
        cout << "st";
        break;
    case 2: case 22:
        cout << "nd";
        break;
    case 3: case 23:
        cout << "rd";
        break;
    default:
        cout << "th";
        break;
    }
    cout << endl;
    return 0;
}

if-ordinal.cpp

The same program, written using if/else instead of switch.

#include <iostream>
using namespace std;
int main()
{
    int day;
    cout << "Enter day of month: ";
    cin >> day;

    cout << "October " << day;
    if(day == 1 ||
       day == 21 ||
       day == 31)
    {
        cout << "st";
    }
    else if(day == 2 || day == 22) {
        cout << "nd";
    }
    else if(day == 3 || day == 23) {
        cout << "rd";
    }
    else {
        cout << "th";
    }
    cout << endl;
    return 0;
}