An ordinal number shows a relative position, e.g., 1st, 2nd, 3rd, 4th,etc. In other words, ordinal numbers series are the words representing the rank of a number with respect to some order, in particular order or position. To evaluate this, we have taken the modulus of the specified number by dividing it with 10 and 100. After that we have subtracted both the modulus. Then we have checked whether the resulted value is 10,if it is, then number is returned with "th". We have made cases that if the modulus of a number by dividing it with 10 is 1, it will returned "st" , if 2, it will returned "nd", if 3, it will returned "rd" and for the rest, it will returned "th". Here we are going to display first 10 ordinal numbers.

**Here is the code:**

public class OrdinalNumber { public static String ordinalNo(int value) { int hunRem = value % 100; int tenRem = value % 10; if (hunRem - tenRem == 10) { return "th"; } switch (tenRem) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; default: return "th"; } } public static void main(String[] args) { OrdinalNumber number = new OrdinalNumber(); for (int i = 1; i <= 10; i++) { String st = number.ordinalNo(i); System.out.println(i + " = " + i + st); } } }

**Output**

1 = 1st 2 = 2nd 3 = 3rd 4 = 4th 5 = 5th 6 = 6th 7 = 7th 8 = 8th 9 = 9th 10 = 10th

Advertisements

Posted on: November 17, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms. Connect Me on Google+