In their 1977 work "The Early Development of Programming Languages", Trabb Pardo and Knuth introduced a trivial program which involved arrays, indexing, mathematical functions, subroutines, I/O, conditionals and iteration. They then wrote implementations of the algorithm in several early programming languages to show how such concepts were expressed.
The simpler Hello world program has been used for much the same purpose.
ask for 11 numbers into sequence S
reverse sequence S
for each item in sequence S
do an operation
if result overflows
alert user
else
print result
The algorithm reads eleven numbers from an input device, stores them in an array, and then processes them in reverse order, applying a user-defined function to each value and reporting either the value of the function or a message to the effect that the value has exceeded some threshold.
begin integer i; real y; real array a[0:10];
real procedure f(t); real t; value t;
f := sqrt(abs(t))+5*t^3;
for i := 0 step 1 until 10 do read(a[i]);
for i := 10 step -1 until 0 do
begin y := f(a[i]);
if y > 400 then write(i, "TOO LARGE")
else write(i,y);
end
end
The problem with the usually specified function is that the term 5*t^3 gives overflows in almost all languages for very large negative values.
def f(x )
return Math.sqrt(x.abs) + 5*x **3
end
def main
Array.new(11) { gets.to_i }.reverse.each do |x|
y = f(x)
puts "#{x} #{(y>400) ? 'TOO LARGE' : y}"
end
end
end
Ruby handles numerical overflow by returning Infinity, which is greater than 400.
let tpk =
let f x = sqrt x +. 5.0 *. (x ** 3.0) in
let pr f = print_endline (if f > 400.0 then "overflow" else string_of_float f) in
let read = float_of_string (read_line ()) in
let a = Array.init 11 (fun _ -> read ()) in
for i = 10 downto 0 do
pr (f a.(i))
done
A functional version can also be written in Ocaml:
let tpk l =
let f x = sqrt x +. 5.0 *. (x ** 3.0) in
let p x = x < 400.0 in
List.filter p (List.map f (List.rev l))