1st, 2nd, and 3th

For your June exercise, you need to concoct code that properly generates an ordinal number. Write a function that returns a string “st” “nd” “rd” or “th” that’s tacked on to any integer value from 1 through what-have-you.

To test the function, write a loop that displays values from 1 through 100. The output would look something like this:

...
21st
22nd
23rd
24th
25th
...

HINT: The first step to devising a solution is to know the rules about making numbers into ordinals in English. Generally speaking:

  • Any value ending in 1 becomes 1st.
  • Any value ending in 2 becomes 2nd.
  • Any value ending in 3 becomes 3rd.
  • Values ending in 4 through 0 end with a th.
  • Values between 11 and 19 all end in th.

Please attempt the exercise before you peek at my solution. Remember that my solution is merely one way of solving the problem.

Exercise Solution

Leave a Reply