The same very simple program in many different programming languages
Archive - Originally posted on "The Horse's Mouth" - 2010-03-31 07:32:37 - Graham EllisI was asked how many languages I teach yesterday - and the answer's quite a few; at times, it's almost "the more the merrier" as to a very great extent they are varieties on a theme much of the way - but different balances of features make some languages especially good for some uses.
As a geek's relaxation after some very heavy days, I have just taken a very simple example - a loop counting downwards - from yesterday's Lua course, and recoded it into a number of different languages - I'll share the code here:
In C
#include <stdio.h>
main() {
int k;
for (k=10; k>=1; k--) {
printf("%d\n",k);
}
}
C Courses - Source of this example
In C++
using namespace std;
#include <iostream>
main() {
int k;
for (k=10; k>=1; k--) {
cout << k << endl;
}
}
C++ Courses - Source of this example
In Java
public class revl {
public static void main(String [] args) {
int k;
for (k=10; k>=1; k--) {
System.out.println(k);
}
}
Java Courses - Source of this example
}
In Lua
for k=10,1,-1 do
print (k)
end
Lua Courses - Source of this example
In PHP
<?php
for ($k=10; $k>=1; $k--) {
print ("$k\n");
}
?>
PHP Courses - Source of this example
In Perl
for ($k=10; $k>=1; $k--) {
print ("$k\n");
}
Perl Courses - Source of this example
In Python
for k in range(10,0,-1):
print k
Python Courses - Source of this example
In Ruby
for k in 1..10
print ("#{11-k}\n")
end
Ruby Courses - Source of this example
In Shell (works in ksh and bash)
let a=10
while [[ $a -ge 1 ]] ; do
echo $a
let a-=1
done
Linux / Unix / Shell Courses - Source of this example
and in Tcl
set k 10
while {$k >= 1} {
puts $k
incr k -1
}
Tcl, Tk, Expect Courses - Source of this example
In Summary ... there are many ways of doing something like this in all of the languages - the examples above are not necessarily best practise, but they give you an idea of programs, loops, variables, and how they compare. I could have added Javascript, XSLT, Fortran, C Shell, Basic and perhaps a few others - but the above are just the languages I happened to have on the machine I was using - one of our teaching machines - and I could test them quickly. Did someone mention awk ...