View Problem

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
DiskEdit
csharp .Net 2.0 or later
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
case 2:
return i.ToString() + "nd";
case 3:
return i.ToString() + "rd";
default:
return i.ToString() + "th";
}
}
DiskEdit
csharp .Net 1.0 or 1.1
public static string GetOrdinal(int i)
{
if (i > 10 && i < 20) return i.ToString() + "th";
switch (i % 10)
{
case 1:
return i.ToString() + "st";
break;
case 2:
return i.ToString() + "nd";
break;
case 3:
return i.ToString() + "rd";
break;
default:
return i.ToString() + "th";
break;
}
}
DiskEdit
erlang
Suffix = case Num of
N when N > 10, N < 20 -> "th";
N when N rem 10 =:= 1 -> "st";
N when N rem 10 =:= 2 -> "nd";
N when N rem 10 =:= 3 -> "rd";
_ -> "th"
end,
io_lib:format("~w~s", [Num, Suffix])
DiskEdit
cpp Turbo C++
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,i,x;
cout<<"Enter the range:";
cin>>num;
for(i=1;i<=num;i++)
{
x=i%10;
switch(i)
{
case 11:
case 12:
case 13:cout<<i<<"th ";
continue;
}
switch(x)
{
case 1: cout<<i<<"st ";break;
case 2: cout<<i<<"nd ";break;
case 3: cout<<i<<"rd ";break;
default: cout<<i<<"th ";
}
}
getch();
}
ExpandDiskEdit
fantom
suffix := |Int n -> Str|
{
if ((4..20).contains(n % 100))
return "th"

switch((n.toStr)[-1])
{
case '1': return "st"
case '2': return "nd"
case '3': return "rd"
default: return "th"
}
}

(1..40).each { echo("$it${suffix(it)}") }

Submit a new solution for csharp, erlang, cpp, or fantom
There are 11 other solutions in additional languages (clojure, fsharp, groovy, haskell ...)