View Category
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.
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
System.out.println("Hello, Bob!");
}
csharp
if (name == "Bob") Console.WriteLine("Hello, {0}!", name);
clojure
(def person "Bob")
(if (= person "Bob")
(println "Hello, Bob!"))
(if (= person "Bob")
(println "Hello, Bob!"))
fsharp
if name = "Bob" then printfn "Hello, %s!" name
name = "Bob" && begin printfn "Hello, %s!" name ; true end
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"
java
if (age > 42) {
System.out.println("You are old");
} else {
System.out.println("You are young");
}
System.out.println("You are old");
} else {
System.out.println("You are young");
}
System.out.println("You are " + ((age>42)?"old":"young"));
csharp
int age = 41;
if (age > 42)
System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");
if (age > 42)
System.Console.WriteLine("You are old");
else
System.Console.WriteLine("You are young");
clojure
(def age 41)
(if (> age 42) "You are old" "You are young")
(if (> age 42) "You are old" "You are 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
printfn "You are %s" message
Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)
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");
else if (age > 30) System.out.println("You are middle-aged");
else System.out.println("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");
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"));
clojure
(println
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
(condp <= age
84 "You are really ancient"
30 "You are middle aged"
"You are young"))
fsharp
if age > 84 then printfn "You are really ancient"
elif age > 30 then printfn "You are middle-aged"
else printfn "You are young"
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
| _ when age > 84 -> "really ancient"
| _ when age > 30 -> "middle-aged"
| _ -> "young"
printfn "You are %s" message
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
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";
}
}
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";
}
}
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";
}
}
{
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;
}
}
{
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;
}
}
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")))))
(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")))))
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))
| 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))
Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)
Starting with a variable x=1, Print the sequence
"1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
java
int x = 1;
while (x < 150) {
System.out.println(x+",");
x*=2;
}
while (x < 150) {
System.out.println(x+",");
x*=2;
}
csharp
int x = 1;
while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
while (x < 150)
{
x *= 2;
Console.Write("{0},", x);
}
clojure
(take-while #(< % 150) (iterate #(* 2 %) 1))
fsharp
let mutable x = 1
while x < 150 do printf "%d, " x ; (x <- x * 2) done
while x < 150 do printf "%d, " x ; (x <- x * 2) done
// The problem is clearly geared towards imperative languages ;-)
// No need to mutate any variable, here's how to do it loop-free functional:
let rec powers2 i = seq { if i < 150 then yield i; yield! powers2 (i*2) }
powers2 1 |> Seq.iter (fun i -> printf "%i, " i)
// No need to mutate any variable, here's how to do it loop-free functional:
let rec powers2 i = seq { if i < 150 then yield i; yield! powers2 (i*2) }
powers2 1 |> Seq.iter (fun i -> printf "%i, " i)
Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)
Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be
"4,2,1,2,6"
java
int rnd;
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);
csharp
System.Random die = new System.Random();
int roll;
do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);
int roll;
do
{
roll = die.Next(1, 6);
Console.Write(roll);
if (roll < 6) Console.Write(",");
}
while (roll != 6);
clojure
(loop [r (rand-int 6)]
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
(if (= r 5)
nil
(do
(println r)
(recur (rand-int 6)))))
fsharp
open System
let rand = Random()
Seq.initInfinite (fun _ -> rand.Next(1, 7))
|> Seq.takeWhile (fun x -> x < 6)
|> fun items -> String.Join(",", items)
|> function s when s = "" -> printfn "6" | s -> printfn "%s,6" s
let rand = Random()
Seq.initInfinite (fun _ -> rand.Next(1, 7))
|> Seq.takeWhile (fun x -> x < 6)
|> fun items -> String.Join(",", items)
|> function s when s = "" -> printfn "6" | s -> printfn "%s,6" s
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
java
for(int i=0;i<5;i++) {
System.out.print("Hello");
}
System.out.print("Hello");
}
csharp
string text = "Hello";
for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
for (int i = 0; i < 5; i++)
{
Console.Write(text);
}
clojure
(dotimes [_ 5]
(print "Hello"))
(print "Hello"))
fsharp
for i = 1 to 5 do printf "Hello" done
dotimes 5 (fun () -> printf "Hello")
// Repetition via ranging over a List type(index ignored)
for _ in list do printf "Hello" done
for _ in list do printf "Hello" done
// Repetition via ranging over a Sequence type(index ignored)
for _ in sequence do printf "Hello" done
for _ in sequence do printf "Hello" done
// Repetition via ranging over an Array type(index ignored)
for _ in array do printf "Hello" done
for _ in array do printf "Hello" done
Perform an action a fixed number of times with a counter
Display the string
"10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
java
for(int i=10; i>=1; i--) {
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
csharp
for (int i = 10; i > 0; i--)
{
Console.Write("{0} .. ", i);
}
Console.WriteLine("Liftoff!");
{
Console.Write("{0} .. ", i);
}
Console.WriteLine("Liftoff!");
clojure
(dotimes [i 10]
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
(print (str (- 10 i) " .. ")))
(println "Liftoff!")
fsharp
for i = 10 downto 1 do printf "%d .. " i done
printfn "Liftoff!"
printfn "Liftoff!"
// Repetition via ranging over a Sequence type
for i in {10 .. -1 .. 1} do printf "%d .. " i done ; printfn "Liftoff!"
for i in {10 .. -1 .. 1} do printf "%d .. " i done ; printfn "Liftoff!"
