Mohanapriya R Mohanapriya R
Updated date Jul 04, 2024
In this article, we will learn how to convert ordinal numbers like "first", "second", and "third" into their numerical equivalents using C#.

Converting Ordinal to Number in C#

Ordinal numbers represent the position or rank of an item in a sequence, such as "first," "second," "third," and so on. They provide a way to organize and describe the order of elements in a list or series.

To convert ordinal numbers to numerical values in C#, we can use a simple mapping approach. We will create a function that takes an ordinal number as input and returns its corresponding numerical value. 

using System;

class Program
{
    static int ConvertOrdinalToNumber(string ordinal)
    {
        switch (ordinal.ToLower())
        {
            case "first":
                return 1;
            case "second":
                return 2;
            case "third":
                return 3;
            // Add more cases for other ordinal numbers as needed
            default:
                throw new ArgumentException("Invalid ordinal number");
        }
    }

    static void Main(string[] args)
    {
        string ordinal = "third";
        int number = ConvertOrdinalToNumber(ordinal);
        Console.WriteLine($"The ordinal '{ordinal}' corresponds to the number {number}");
    }
}

We have defined a ConvertOrdinalToNumber function that takes an ordinal number as input and returns its numerical value. We used a switch statement to handle different cases such as "first," "second," and "third," converting them to their corresponding numbers. 

Output:

The ordinal 'third' corresponds to the number 3

Comments (0)

There are no comments. Be the first to comment!!!