View Subcategory

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
ruby
if (name=='Bob')
puts "Hello, Bob!"
end
puts "Hello, Bob!" if name=='Bob'
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
perl
if ($name eq "Bob") {
print "Hello, Bob!"
}
print "Hello, Bob!" if $name eq "Bob";
groovy
if (name=='Bob')
println "Hello, Bob!"
scala
val name = "Bob"
if (name.equals("Bob")) printf("Hello, %s!\n", name)
val name = "Bob"

// Scala supports operator overloading, so the following works correctly
if (name == "Bob") printf("Hello, %s!\n", name)
python
if name == 'Bob':
print 'Hello, Bob!'
cpp
if (name == "Bob") Console::WriteLine("Hello, {0}!", name);
if (name == "Bob") std::cout << "Hello, " << name << "!" << std::endl;
fsharp
if name = "Bob" then printfn "Hello, %s!" name
name = "Bob" && begin printfn "Hello, %s!" name ; true end
erlang
if (Name == "Bob") -> io:format("Hello, ~s!~n", [Name]) ; true -> false end.
case Name of "Bob" -> io:format("Hello, ~s!~n", [Name]) ; _ -> false end.
Name == "Bob" andalso (begin io:format("Hello, ~s!~n", [Name]), true end).
ocaml
if name = "Bob"
then print_string "Hello, Bob!"
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);
php
if($name == "Bob") {
echo "Hello, Bob!";
}
haskell
name = "Bob"
main = if name == "Bob" then putStrLn "Hello, Bob!" else return ()
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
fantom
if (name=="Bob") echo("Hello, Bob!")
go
if name == "Bob" {
fmt.Println("Hello", name)
}

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
ruby
if (age > 42)
puts "You are old"
else
puts "You are young"
end
puts (age>42) ? "You are old" : "You are young"
puts "You are #{age > 42 ? "old" : "young"}"
java
if (age > 42) {
System.out.println("You are old");
} else {
System.out.println("You are young");
}
System.out.println("You are " + ((age>42)?"old":"young"));
perl
if ($age > 42) {
print "You are old"
}
else {
print "You are young"
}
print 'You are ',($age > 42) ? 'old' : 'young';
groovy
if (age > 42)
println "You are old"
else
println "You are young"
println "You are " + (age > 42 ? "old" : "young")
scala
val age = 42
if (age > 42) println("You are old") else println("You are young")
println( "You are " + ( if ( age > 42 ) "old" else "young" ) )
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or 'You are young'
cpp
if (age > 42) Console::WriteLine("You are old");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 42 ? "old" : "young"));
std::printf("You are %s\n", (age > 42 ? "old" : "young"));
fsharp
if age > 42 then printfn "You are old" else printfn "You are young"
let message = if age > 42 then "old" else "young"
printfn "You are %s" message
erlang
if Age > 42 -> io:format("You are old~n") ; true -> io:format("You are young~n") end.
Message = if Age > 42 -> "old" ; true -> "young" end, io:format("You are ~s~n", [Message]).
case Age > 42 of true -> io:format("You are old~n") ; false -> io:format("You are young~n") end.
case Age of _ when Age > 42 -> io:format("You are old~n") ; _ -> io:format("You are young~n") end.
Message = case Age of _ when Age > 42 -> "old" ; _ -> "young" end, io:format("You are ~s~n", [Message]).
Age > 42 andalso (begin io:format("You are old~n"), true end) orelse (begin io:format("You are young~n"), true end).
(fun (X) when X > 42 -> io:format("You are old~n"); (_) -> io:format("You are young~n") end)(Age).
(fun () when Age > 42 -> io:format("You are old~n"); () -> io:format("You are young~n") end)().
io:format("You are ~s~n", [if Age > 42 -> "old" ; true -> "young" end]).
ocaml
if age > 42
then print_string "You are old"
else print_string "You are young"
csharp
int age = 41;

if (age > 42)

System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");


php
if($age < 42) {
echo "You are young";
} else {
echo "You are old";
}
echo "You are " . (($age < 43) ? "young" : "old");
haskell
putStrLn ("You are " ++ if age > 42 then "old" else "young")
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
fantom
if (age > 42)
echo("You are old")
else
echo("You are young")
echo((age > 42) ? "You are old" : "You are young")

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

ruby
if age > 84
puts "You are really ancient"
elsif age > 30
puts "You are middle-aged"
else
puts "You are young"
end
case
when age > 84 then puts "You are really ancient"
when age > 30 then puts "You are middle-aged"
else puts "You are young"
end
java
if (age > 84) System.out.println("You are really ancient");
else if (age > 30) System.out.println("You are middle-aged");
else System.out.println("You are young");
perl
if ($age > 84) {
print "You are really ancient";
} elsif ($age > 30) {
print "You are middle-aged";
} else {
print "You are young";
}
print 'You are ',
$age > 84 ? 'really ancient!'
: $age > 30 ? 'middle-aged'
: 'young';
groovy
if (age > 84)
println "You are really ancient"
else if (age > 30)
println "You are middle-aged"
else
println "You are young"
scala
val age = 65

if (age > 84) println("You are really ancient")
else if (age > 30) println("You are middle-aged")
else println("You are young")
python
if age > 84:
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'
cpp
if (age > 84) Console::WriteLine("You are really ancient");
else if (age > 30) Console::WriteLine("You are middle-aged");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young"));
std::cout << "You are " << (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young") << std::endl;
fsharp
if age > 84 then printfn "You are really ancient"
elif age > 30 then printfn "You are middle-aged"
else printfn "You are young"
let message = match age with
| _ when age > 84 -> "really ancient"
| _ when age > 30 -> "middle-aged"
| _ -> "young"
printfn "You are %s" message
erlang
if
Age > 84 -> io:format("You are really ancient~n");
Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
case Age of
_ when Age > 84 -> io:format("You are really ancient~n");
_ when Age > 30 -> io:format("You are middle-aged~n");
true -> io:format("You are young~n")
end.
ocaml
if age > 84 then
print_endline "You are really ancient"
else if age > 30 then
print_endline "You are middle-aged"
else
print_endline "You are young"
csharp
if (age > 84) Console.WriteLine("You are really ancient");
else if (age > 30) Console.WriteLine("You are middle-aged");
else Console.WriteLine("You are young");
Console.WriteLine("You are {0}", ((age > 84) ? "really ancient" : (age > 30) ? "middle-aged" : "young"));
php
echo "You are " . (($age > 84) ? "really ancient" : (($age > 30) ? "middle-aged" : "young"));
$response = "You are ";
if ($age > 84) {
$response .= "really ancient";
} else if ($age > 30) {
$response .= "middle-aged";
} else {
$response .= "young";
}
echo $response;
haskell
f age
| age > 84 = putStrLn "You are really ancient"
| age > 30 = putStrLn "You are middle-aged"
| otherwise = putStrLn "You are young"

main = f age
where age = 31
clojure
(println
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
fantom
if (age > 84)
echo("You are really ancient")
else if (age > 30)
echo("You are middle-aged")
else
echo("You are young")

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
ruby
def suffixed(number)
last_digit = number.to_s[-1..-1].to_i
suffix = case last_digit
when 1 then 'st'
when 2 then 'nd'
when 3 then 'rd'
else 'th'
end
suffix = 'th' if (11..13).include?(number)
"#{number}#{suffix}"
end

(1..40).each {|n| puts suffixed(n) }
java
String[] array = new String[40];
for(int n = 1; n <= array.length; n++)
array[n-1] = Integer.toString(n);
for(int n = 0; n < array.length; n++)
{
int y = Integer.parseInt(array[n]);
if(array[n].length() > 1)
y = Integer.parseInt(array[n].substring(1));
switch(y)
{
case 1: {array[n] += "st"; break;}
case 2: {array[n] += "nd"; break;}
case 3: {array[n] += "rd"; break;}
default: array[n] += "th";
}
}
perl
sub suffix {
my $n = shift;

return 'th' if $n % 100 >= 4 && $n % 100 <= 20;
return 'st' if $n % 10 == 1;
return 'nd' if $n % 10 == 2;
return 'rd' if $n % 10 == 3;
return 'th';

}

foreach my $n (1..40) {
print $n.suffix($n)."\n";
}
groovy
def suffix(n) {
switch(n) {
case { n % 100 in 4..20 } : return 'th'
case { n % 10 == 1 } : return 'st'
case { n % 10 == 2 } : return 'nd'
case { n % 10 == 3 } : return 'rd'
default : return 'th'
}
}
(1..40).each { n ->
println "$n${suffix(n)}"
}
scala
object FourToTwenties {
def unapply (n: Int) = (4 to 20).contains(n % 100)
}

def suffix (n: Int) = {
n match {
case FourToTwenties() => "th"
case n if n % 10 == 1 => "st"
case n if n % 10 == 2 => "nd"
case n if n % 10 == 3 => "rd"
case _ => "th"
}
}

for (n <- 1 to 40) {
println(n.toString + suffix(n))
}

python
def affix(num):
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num

print [affix(x) for x in xrange(1,41)]

cpp
#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();
}
fsharp
let suffix = function
| n when n > 10 && n < 20 -> "th"
| n when n % 10 = 1 -> "st"
| n when n % 10 = 2 -> "nd"
| n when n % 10 = 3 -> "rd"
| _ -> "th"

seq { 1 .. 40 }
|> Seq.iter (fun n -> printfn "%i%s" n (suffix n))
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])
ocaml
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x when x mod 10 = 1 -> "st"
| x when x mod 10 = 2 -> "nd"
| x when x mod 10 = 3 -> "rd"
| _ -> "th"
;;
(* alternate implementation without using guards:
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x -> match x mod 10 with
| 1 -> "st"
| 2 -> "nd"
| 3 -> "rd"
| _ -> "th"
*)

for i = 1 to 40 do
Printf.printf "%d%s " i (numsuffix i);
done;
print_newline ()
csharp
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";
}
}
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;
}
}
php
function suffix($n) {
switch ($n) {
case ($n % 100 >= 4) && ($n % 100 <= 20):
return 'th';
case $n % 10 == 1:
return 'st';
case $n % 10 == 2:
return 'nd';
case $n % 10 == 3:
return 'rd';
default:
return 'th';
}
}
for ($n=1; $n<=40; $n++) {
echo $n . suffix($n) ."\n";
}
haskell
suffixed n = show n ++ suffix
where
suffix
| n `mod` 100 `div` 10 == 1 = "th"
| otherwise = case n `mod` 10 of
1 -> "st"
2 -> "nd"
3 -> "rd"
_ -> "th"


result = map suffixed [1..40]
clojure
(def n 112)

(println (str n
(let [rem (mod n 100)]
(if (and (>= rem 11) (<= rem 13))
"th"
(condp = (mod n 10)
1 "st"
2 "nd"
3 "rd"
"th")))))
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)}") }