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.
perl
if ($name eq "Bob") {
print "Hello, Bob!"
}
print "Hello, Bob!" if $name eq "Bob";
ruby
if (name=='Bob')
puts "Hello, Bob!"
end
puts "Hello, Bob!" if name=='Bob'
python
if name == 'Bob':
print 'Hello, Bob!'
java
if (name.equals("Bob")) {
System.out.println("Hello, Bob!");
}
php
if($name == "Bob") {
echo "Hello, Bob!";
}

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"
perl
if ($age > 42) {
print "You are old"
}
else {
print "You are young"
}
print 'You are ',($age > 42) ? 'old' : '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"}"
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or '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 " + ((age>42)?"old":"young"));
php
if($age < 42) {
echo "You are young";
} else {
echo "You are old";
}
echo "You are " . (($age < 43) ? "young" : "old");

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

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';
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
python
if age > 84:
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'
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");
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;

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
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";
}
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) }
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)]

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";
}
}
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";
}

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.
perl
my $x = 1;
while($x < 150) {
print $x, ",";
$x *=2
}
ruby
x=1
while x < 150
puts x
x <<= 1
end
python
x = 1
while x < 150:
print '%s, ' % x,
x *= 2
java
int x = 1;
while (x < 150) {
System.out.println(x+",");
x*=2;
}
php
$x = 1;
while($x < 150) {
echo "$x,";
$x *= 2;
}
$x = 0;
$c = pow(2, $x);
while($c < 150) {
echo "$c,";
$c = pow(2, $x++);
}

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"
perl
do {
my $number = int(rand(6)+1);
print $number;
print ',' if ($number != 6);
} while ($number != 6);
ruby
# Ruby has no DO..WHILE construct. Need to write it as a WHILE
rnd = 0
while (rnd != 6)
rnd = rand(6)+1
print rnd
print "," if (rnd!=6)
end
begin
rnd = rand(6)+1
print rnd
print "," if rnd!=6
end while rnd != 6
# This uses Enumerators, ad it becomes almost functional style...

games = Enumerator.new do |yielder|
yielder.yield rand(6) + 1 while true
end

puts games.take_while {|roll| roll != 6}.join(",")
python
import random, itertools

def dice():
while True:
yield random.randint(1,6)

print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))
java
int rnd;
do {
rnd = (int)(Math.random()*6)+1;
System.out.print(rnd);
if (rnd!=6) {
System.out.print(",");
}
} while(rnd!=6);
php
do {
$rand = rand(1,6);
echo $rand;
if ($rand != 6) echo ", ";
} while ($rand != 6);

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
perl
print "Hello" x 5
print "Hello" for (1..5)
ruby
puts "Hello"*5
5.times { print "Hello" }
python
print "Hello" * 5
for i in range(5):
print "Hello"
java
for(int i=0;i<5;i++) {
System.out.print("Hello");
}
php
for($i = 0; $i < 5; $i++) {
echo "Hello";
}

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!"
perl
for (my $i = 10; $i > 0; $i--) {
print "$i .. ";
}
print "Liftoff!";
print "$_ .. " for reverse 1..10;
print "Liftoff!";
ruby
10.downto(1) { |n| print n, " .. " }
puts "Liftoff!"
python
print " .. ".join(str(i) for i in range(10, 0, -1)), ".. liftoff!"
java
for(int i=10; i>=1; i--) {
System.out.print(i + " .. ");
}
System.out.print("Liftoff!");
php
for($i = 10; $i > 0; $i--) {
echo $i." .. ";
}
echo "Liftoff!";