Ordinal Numbers Series Program in Java


 

Ordinal Numbers Series Program in Java

An ordinal number shows a relative position, e.g., 1st, 2nd,3rd, 4th,etc.In this section, you will learn how to display first 10 ordinal number.

An ordinal number shows a relative position, e.g., 1st, 2nd,3rd, 4th,etc.In this section, you will learn how to display first 10 ordinal number.

Ordinal Numbers Series Program in Java

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

Ads