Raiding the Lost Average

This is an old hobby of mine: to write some silly thing in as many programming languages as possible.

Here we calculate averages. Not all of these are tested, and even when they are, they are not guaranteed to work on any particular platform or with any particular dialect.

I have tried to preserve each language’s distinctive “flavour”, even when it means that the programs won’t be used the same way. Most of the code samples still read standard input (or the keyboard input, whichever is more appropriate) and spit out the result on screen. Some, especially the ones coded in a “functional” language, just define functions to be used in whatever manner is the most appropriate to the language.

See also Raiding the Lost Lottery Line.

ABC

ABC

ABC was designed for the same purpose as Pascal and BASIC in their turns: to be an easy-to-learn language with which it would be very difficult to fall into bad programming habits. BASIC failed, and since there is no comment statement in ABC as far as I know, I hardly think you could call ABC victorious either. Anyway, this was the predecessor of Python.

As you can see, number 0 stands for end of input. That means 0 cannot be included in the list of values you want to get the average of; but in an interpreting environment this is the easiest way round. No serious piece of programming this one.

PUT 1 IN number
WHILE number <> 0:
    WRITE "Give a number, 0 to quit: "
    READ number EG 0
    PUT sum + number IN sum
    PUT n + 1 IN n
PUT n - 1 IN n
PUT sum / n IN average
WRITE "Average =", average
Ada

Ada

Ada is a high-level procedural language much like C and Pascal. It has been developed by and for the US government, and sometimes it’s been called the world’s first “paranoid” programming language as it puts much emphasis on data protection.

This example is totally untested and (I’m actually quite sure it’s still not 100% correct).

-- Calculating average in Ada

with Ada.Text_IO;
use Ada.Text_IO;

n : INTEGER := 0;
number : FLOAT := 1.0;
sum : FLOAT := 0.0;

begin CalcAverage
    while number != 0.0 loop
        Text_IO.Put("Give a number, or 0 to quit: ");
        Text_IO.Get(number);
        n := n + 1;
        sum := sum + number;
    end loop;
    n := n - 1;
    average := sum / n;
    Text_IO.Putline("Average = ", average);
end CalcAverage;
Algol

Algol

This snippet I admit having stolen elsewhere. I only changed the initial comment. The main reason for this is simple: even the real author of this snippet complains about the “inability to locate the necessary compiler”. It is to expected, then, that this snippet is very different from the rest of them: for one thing, it does not take or accept its input from elsewhere. The I/O functions were actually never formally defined for Algol but were implementation-specific.

However, I consider an Algol example quite essential for this page. As can easily be seen, Algol is the ancestor of both Pascal and C, although it also had advanced structures (such as the ternary if…then…else in the assignment to Data[i]) below) that were not brought over to them. (Actually, the newer versions of Python have exactly the same construct!)

// Calculating average in Algol

begin
  integer N;
  Read Int(N);

  begin
    real array Data[1:N];
    real sum, avg;
    integer i;
    sum:=0;

    for i:=1 step 1 until N do
      begin real val;
        Read Real(val);
        Data[i]:=if val<0 then -val else val
      end;

    for i:=1 step 1 until N do
      sum:=sum + Data[i];
    avg:=sum/N;
    Print Real(avg)
  end
end
AWK

AWK

AWK is a text-scanning, not a general-purpose programming language. Since AWK programs always have an implicit input loop, there is no need to write an input routine: we just have to make sure the data obtained is valid.

Previously, I had here a version that only expected one number per input line—I said we shouldn’t bother about anything more refined. Well, now I’ve refined it. In effect, this script can slurp in any text file and ultimately produce an average of all the numbers found inside it, negative ones included, unlike before.

# Calculating average in AWK

/-?[0-9]+.?[0-9]*/ {
    for (p = 1; p <= NF; p ++)
        if ($p ~ /^-?[0-9]+.?[0-9]*$/) {
            sum += $p
            n ++
        }
}

END {
    average = sum / n
    printf("Average = %f\n", average)
}
BASIC

BASIC

Here I tried to approximate the feeling of very primitive BASIC: no advanced loop control, just a GOTO clause forcing the control to move to a given line number—the so-called “spaghetti BASIC”. Later BASICs got very close to, say, Pascal.

There were a few commonly used abbreviations in later BASICs, too. For instance, PRINT was typed ? to save a couple of bytes of precious memory, and GOTO was redundant after THEN for the same reason. END clause is optional when there was no need to end the run prematurely.

0 again stands for the end-of-input, as in the ABC code.

100 REM Calculating average in BASIC
110 REM
120 PRINT "Give a number, 0 to quit: ";
130 INPUT F
140 S=S+F
150 N=N+1
160 IF F<>0 THEN GOTO 120
170 N=N-1
180 A=S/N
190 PRINT "Average ="; A
200 END
C

C

Nothing remarkable here except the eyesore syntax, at least when compared to Pascal or Python.

I think there is no reason to prompt the user as in the ABC etc. samples, since C programs can easily read the standard input.

Note: After many long years, I finally decided to make this code to work right. Previously, this followed the “BASIC strategy”, i.e., read until 0 was input. Now it reads until EOF which is much more sensible.

/* Calculating average in C */

#include <stdio.h>

void main(void)
{
    double number, sum = 0.0, average;
    int n;

    for (n = 0; scanf("%lf", &number) == 1; sum += number, n ++)
        ;
    average = sum / n;
    printf("Average = %lf\n", average);
}
C++

C++

This is hardly any different from C except in minor points. In a program of this size, there is no gain in utilizing the object-orientedness of the language.

C++ standards have changed lately, so I have had to modify the following a bit; nowadays it’s obligatory to specify namespaces.

// Calculating average in C++

#include <iostream>

int main(void)
{
    double number = 1.0, sum = 0.0, average;
    int n;

    for (n = 0; number; n ++, sum += number)
        std::cin >> number;
    average = sum / -- n;
    std::cout << "Average =" <<  average << std::endl;
    return(0);
}
COBOL

COBOL

As in my samples in other languages, I have tried to find the “true” COBOL here, which means going back in time a bit.

0 stands for end of input. Cf. ABC.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. CALC-AVERAGE.
      *
      * Calculating average in COBOL
      *
       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
           NUMBER     PIC 999999.999 VALUE 0.
           SUM        PIC 9999999.9999 VALUE 0.
           N          PIC 99 VALUE 0.
           AVERAGE    PIC ZZZZZZ9.9ZZZ VALUE 0.
       PROCEDURE DIVISION.
       MAIN SECTION.
           PERFORM SUM-FIGURES UNTIL FIGURE EQUALS TO 0.
           DIVIDE SUM BY N GIVING AVERAGE.
           DISPLAY 'Average =', AVERAGE.
       MAIN-EX.
           EXIT.
           STOP RUN.
       SUM-FIGURES SECTION.
           DISPLAY 'Give a number, 0 to quit: '.
           ACCEPT NUMBER.
           ADD NUMBER TO SUM.
           ADD 1 TO N.
       SUM-FIGURES-EX.
           EXIT.
D

D

D is a newer language. It looks a lot like C/C++ or even Java, and that’s exactly where its syntactic heritage lies. However, D is also a “dot com era” language and has borrowed features from here and there.

// Calculating average in D

import std.stdio;
import std.format;

void main()
{
    ulong n = 0;
    double number, sum = 0, average;

    foreach (char[] line; stdin.byLine()) {
        ++ n;
        formattedRead(line, "%f", &number);
        sum += number;
    }
    average = sum / n;
    writeln("Average = ", average);
}
Erlang

Erlang

Erlang is a newer functional language. It was conceived by Ericsson for robust handling of telecom switches. The idea behind the following closely resembles other functional languages such as Haskell or Ocaml.

%% Calculating average in Erlang

-module(avg).
-export([sum/1, avg/1]).

sum([]) ->
    0;
sum([First|Rest]) ->
    First + sum(Rest).

avg([]) ->
    0;
avg(L) ->
    sum(L) / length(L).
Forth

Forth

As becomes the Forth ideology, this is a one-liner. Adherents in other languages may want to use indentations and such to point out the structure. The input-output ideology tries to be as much “Forthish” as possible: there is neither input nor output here. The “word” created in the sample expects to find its input in the stack when it is called, and the answer is left in the stack when done.

What happens? First we get the depth of the stack, i.e., the number of items in it. The value goes to the top of the stack, where we duplicate it since we’ll be needing it twice. One of these values is put in the “return stack” with >r where it will be safe for a while. Now we go to a loop from 1 to depth which we still have on the stack ready to be used. The body of the loop is between the do and loop: we sum all the values we find in the stack (the depth value was already eaten up by do). Finally we get the saved value from the return stack with r>. Now there are only two values left in the stack: the sum and the depth, so we divide the former with the latter, leaving the result on the stack.

(Wow, that takes so much longer in English!)

\ Calculating average in Forth ( n1 n2 ... -- n )
: avg depth dup >r 1 do + loop r> / ;
Fortran

Fortran

Old-fashioned Fortran, here, but not so old-fashioned that we should use the predefined variable names (i etc. for integers, f etc. for floats and so on).

0 stands for end of input. Cf. ABC.

c    Calculating average in Fortran
     program average
     real f, s, a
     integer n
     s=0
     n=0
10   write (*,*) 'Give a number, 0 to quit:'
     read (*,*) f
     s=s+f
     n=n+1
     if (f.eq.0) goto 10
     n=n-1
     a=s/n
     write (*,*) 'Average =', a
     stop
     end
Go

Go

Google’s Go is one more “dot com era” language to the C-derived family. Unlike C (mostly) but like D, it can be used both interpreted and compiled. Note that variables can go undeclared (like “sum” in this example), if you use Pascal-like “:=” to initialize them. Normally variables are set to a value with “=”, as in C.

// Calculating average in Go

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var line string
    var number float64

    sum := 0.0
    n := 0
    for {
        _, err := fmt.Scan(&line)
        if err != nil {
            break
        }
        number, err = strconv.ParseFloat(line, 64)
        if err == nil {
            sum += number
            n ++
        }
    }
    average := sum / float64(n)
    fmt.Println("Average =", average)
}
Haskell

Haskell

Haskell is a purely-functional programming language.

The example given doesn’t have any I/O: it only specifies the function to be called when calculating the average of a list of floats.

-- Calculating average in Haskell

avg :: [Float] -> Float
avg [] = 0
avg xs = sum xs `div` length xs
Icon

Icon

Icon can be notoriously cryptic when used by real gurus. It has ingenious control structures that do not return a value but signal failure or success, which makes it very easy to hide value-checking inside ordinary statements.

In my sample here, there is no need to write an explicit end-of-loop test in the while clause, since read() fails when no more input is available, and that makes while fail (and end) too.

# Calculating average in Icon

procedure main()
    sum := n := 0
    while sum +:= read() do n +:= 1
    write("Average = ", average := sum / n)
end
J

J

J is a successor to APL, one of the oddest programming languages ever designed (at least for serious purposes). Visually the two languages don’t look much like each other because J tries to not repeat the “mistake” of APL: using an obscure character set that needs to be independently implemented. Instead, plain ASCII characters are used. On the other hand, conceptually J is quite close to APL.

avg =: +/ % # NB. Calculating average in J
JavaScript

JavaScript

This one expects to be called from somewhere, as befits JavaScript’s Web ideology.

// Calculating average in JavaScript
function calcAverage(l)
{
    for (i = 0; i < calcAverage.arguments.length;
	i ++, sum += calcAverage.arguments[i]) ;
    average = sum / calcAverage.arguments.length;
    document.write('Average =', average);
}
Julia

Julia

Julia is a newish language specialized in high-performance technical computation; this meaning basically that it’s quite fast computationally and somewhat oriented in number crunching. There’s even a builtin function mean() for calculating averages which means that the following example just shows how to read and parse standard input (and that there are list comprehensions).

# Calculating average in Julia

nums = [parse(num) for num in split(readall(STDIN))]
println("Average = ", mean(nums))
KiXtart

KiXtart

A hideous language this one, just one bit better than the extremely nasty MS-DOS batch “language”.

; Calculating average in KiXtart

$number = 1
$sum = 0
$n = 0

WHILE "$number"
    "Give a number, 0 to quit:"
    GET $number
    $sum = $sum + $number
    $n = $n + 1
LOOP

$n = $n - 1
$average = $sum / $n
"Average =" $average
LISP

LISP

“Lots of Idiotic Silly Parentheses”? The syntax is a bit rough for us humans, but still, the ideology in Lisp is quite sound.

I had here previously a version that used eval, but Teemu Likonen proposed me the following, more “Lisp-like” version that uses apply. (One could also use reduce in this particular case, as the purpose is to reduce a list of numbers to a single value, their sum.)

; Calculating average in Common Lisp

(defun average (&rest numbers)
    (/ (apply #'+ numbers) (length numbers)))
Ocaml

Ocaml

This may be somewhat overdone but that’s all right—you can see the idea. First we define a recursive (let rec) function length to get the length of a list, then we define a recursive function sum to calculate the sum of the list, and finally a regular (let) function avg to utilize those two. Note that we have to use distinct float versions of the arithmetic infix operators (+. and /.) to get float results.

(* Calculating average in Ocaml *)

let rec length xs =
    match xs with
      []          -> 0
      | x :: xs'  -> 1 + length xs'

let rec sum xs =
    match xs with
      []          -> 0.
      | x :: xs'  -> x +. sum xs'

let average xs =
    match xs with
      []          -> 0.
      | xs        -> sum xs /. float_of_int (length xs)
Pascal

Pascal

The syntax of Pascal is as lucid as you could hope for. For short tasks as in here, the lucidity tends to give an additional length to the code, but Pascal-adherents worship readability above all. (The same is true of Python.)

{ Calculating average in Pascal }

program CalcAverage(input, output);

var number, sum, average : double;
    n : integer;

begin
    number := 1.0;
    sum := 0.0;
    n := 0;

    while number <> 0 do begin
        write ('Give a number, 0 to quit: ');
        read (number);
        sum := sum + number;
        n := n + 1
    end;
    average := sum / n;
    writeln ('Average =', average)
end.

Here’s a second version that’s tested and works with Free Pascal. It reads standard input until EOF and thus can use zeros as input values.

{ Calculating average in Free Pascal }

program CalcAverage;

uses sysutils;

var stdin: text;
    number, sum, average : double;
    line : string;
    n : integer;

begin
    sum := 0.0;
    n := 0;

    assign(stdin, '');
    reset(stdin);
    while not eof(stdin) do begin
        readln(stdin, line);
        if TryStrToFloat(line, number) then begin
            sum := sum + number;
            n := n + 1
        end
    end;
    close(stdin);
    average := sum / n;
    writeln('Average =', average)
end.
Perl

Perl

Perl is one of the languages with which you can write absolutely unreadable code if so you wish (cf. AWK, Icon). The sample here is an eyesore for all Pascal-lovers, but still pretty easy to number out.

# Calculating average in Perl

for (; <>; $sum += $_, $n ++) {}
$average = $sum / $n;
print "Average = $average\n";
Pilot

Pilot

This example is totally untested, since I don’t have an interpreter for Pilot (though I once even ported one to OS/2!). It’s a silly little language; I wonder whoever thought that language of this kind would be suitable for the educational environment?!

The syntax is extremely crude and simplistic. It can be directly read once you grasp that the one-letter commands are just abbreviations of common English verbs: A for accept, C for compute, J for jump, and T for type.

R:Calculating average in Pilot
*INPUT
T:Give a number, or 0 to quit:
A:#F
C:#S=#S+#F
C:#N=#N+1
J(#F<>0):*INPUT
C:#N=#N-1
C:#A=#S/#N
T:Average = #A
PL/I

PL/I

This one is a real milestone on the bumpy road of programming language history. PL/I paved the road for languages like Pascal and C with its neat procedural syntax.

            /* Calculating average in PL/I */

AVERAGE:    PROCEDURE OPTIONS (MAIN);

            DECLARE (NUMBER, SUM, AVERAGE) FIXED BIN(15);
            DECLARE (N) FIXED BIN(7);

            NUMBER = 1;
            SUM = 0;
            N = 0;

            DO WHILE (NUMBER <> 0);
                PUT SKIP DATA "Give a number, 0 to quit: ";
                GET NUMBER;
                SUM = SUM + NUMBER;
                N = N + 1;
            END DO;

            PUT SKIP DATA "Average =", AVERAGE
END AVERAGE;
Python

Python

Python may be the easiest language for humans to read.

The following example uses standard input, which necessitates the from ... import line. The code requires Python 2 or newer, since the contracted assignment operators (e.g., +=) were borrowed from the C tradition at that time. I think the decision to do that was good: there’s a (deep) semantic difference between modifying an existing value in a variable and assigning it a totally new value. In my mind, n = n + 1 is quite different from n += 1 even though the result is the same.

# Calculating average in Python #1

from sys import stdin

sum = 0.0
for n, line in enumerate(stdin):
    sum += float(line)
average = sum / (n + 1)
print('Average = {0}'.format(average))

The next example uses list comprehension to process the data from the standard input. It requires enough memory to hold the whole file and more, but that will be a problem only with very large files.

First, sys.stdin.readlines() reads the standard I/O until EOF and returns everything in a list of strings. Next, list comprehension is used to create a copy of the (temporary) input buffer where each element is cast into floats. This list is assigned the name nums; and the rest is easy.

# Calculating average in Python #2

from sys import stdin

nums = [float(num) for num in stdin.readlines()]
average = sum(nums) / len(nums)
print('Average = {0}\n'.format(average))
Racket

Racket

Racket is derived from Scheme which in turn is a dialect of Lisp. Racket can run Scheme programs but it also supports many different programming styles; you can actually switch from one Racket style to another just by adding a different #lang directive in the beginning of the source file.

This example shows “typed Racket” which basically means coding in Haskell style.

#lang typed/racket
;;; Calculating average in (typed) Racket

(: average (Number * -> Number))
(define (average . xs)
  (if (null? xs)
      0
      (/ (apply + xs) (length xs))))
REXX

REXX

REXX is a nice well-behaved little language. I used it a lot back in OS/2. The sample should be self-explanatory for all with any familiarity with procedural languages.

/* Calculating average in REXX */

sum = 0.0
n = 0
do loop until number = 0
    pull number
    sum = sum + number
    n = n + 1
end do
n = n - 1
average = sum / n
say "Average =" average
Ruby

Ruby

Ruby is still a newcomer in the field. Being an interpreted language suitable for scripting, it competes primarily with Perl and Python, but unlike them, it’s fully object-oriented. Thus it’s also something like “Smalltalk to the masses”.

Syntactically Ruby is closer to Perl than Python, but it does not inherit the uglyness: variable names do not need to be preceded by silly characters (those which in Perl tell the type of the variable), statements do not need the trailing semicolons, and so on.

Some people see Ruby as the “successor” to Perl—that still remains to be seen, I guess.

# Calculating average in Ruby

sum = 0.0
n = 0
ARGF.each do |line|
    sum += line.to_f
    n += 1
end
average = sum / n
print "Average = #{average}"
Scala

Scala

Scala is a newer language which tries to bring functional programming concepts into general purpose computing. It executes in the Java Virtual Machine (JVM). Programs can in general be quite effortlessly converted from Java to Scala, if not vice versa, because when using idiomatic functional Scala style the programs might be harder to translate to an imperative language. It is also possible to write in Scala almost as if in Java, although almost always Scala programs are still more compact and more to the point.

object Average {
    def main(args: Array[String]) {
        val numbers = for (num <- args) yield try { num.toDouble } catch { case _ => 0.0 }
        println("Average = " + (numbers.reduceLeft(_+_) / numbers.length))
    }
}
Scheme

Scheme

Scheme is the other major variant of Lisp (the other one is Common LISP). Unlike the variants that retain the name “Lisp”, Scheme strives both for syntactic simplicity and syntactic extensibility. It is widely used in education.

The following examples are identical: the second one just uses a syntactic convention with which one lambda can be expressed implicitly.

;;; Calculating average in Scheme #1

(define average
    (lambda (numbers)
        (/ (apply + numbers) (length numbers))))
;;; Calculating average in Scheme #2

(define (average . numbers)
    (/ (apply + numbers) (length numbers)))
sh

sh

The following should work in all UNIX shell flavours that follow the original Bourne shell syntax: sh, bash, ksh, zsh and so on.

#!/bin/sh
# Calculating average in sh (bash, ksh, zsh...)

sum=0
n=0
while read number; do
    if [ ! -z "$number" ]; then
        sum=$(($sum + $number))
        n=$(($n + 1))
    fi
done < /dev/stdin
average=$(($sum / $n))
echo Average = $average
Tcl

Tcl

Speaking of silly languages… Still, Tcl is pretty straigtforward once you get accustomed to the cumbersome notation used when, for example, setting values to variables.

Tcl is often (solely?) used because of its quite usable Tk GUI toolkit, so often in fact that you see the name “Tcl/Tk” mentioned much more often than plain Tcl.

(For years and years, the following code used to be syntactically incorrect. I knew of that but couldn’t run it anywhere to get it right. Now it seems to work at least on my Linux box.)

# Calculating average in Tcl

set number 1
set sum 0
set n 0

while { $number != 0 } {
    puts "Give a number or 0 to quit:"
    gets stdin number
    set sum [ expr $sum + $number ]
    incr n
}
set n [ expr $n - 1 ]
set average [ expr $sum / $n ]
puts stdout "Average = $average"
zsh

zsh

The Z Shell, zsh, is one of the more advanced descendants of the Bourne shell (sh). Nothing very zsh-specific in here, though, just the “(( … ))” notation for handy calculations.

#!/usr/bin/zsh
# Calculating average in ZSH

sum=0
n=0
while read number; do
    if [[ -n $number ]]; then
        (( sum = sum + number ))
        (( n = n + 1 ))
    fi
done < /dev/stdin
(( average = sum / n ))
print Average = ${average}
4DOS

4DOS Batch Language

Perhaps not a fully-fledged programming language, this one…; JP Software’s 4DOS was (and is, now as freeware) an alternative to the extremely cude MS-DOS command interpreter, command.com. It has reincarnated as 4OS2 for OS/2, 4NT for Windows NT, and Take Command for various Windows GUIs, all of which inherit the same syntax.

@echo off
rem Calculating average in 4DOS batch language

setlocal
set sum=0
set n=0
do while %number ne 0
    echo Give a number, or 0 to quit:
    input %%number
    set sum=%@eval[%sum + %number]
    set n=%@eval[%n + 1]
enddo
set n=%@eval[%n - 1]
set average=%@eval[%sum / %n]
echo Average = %average
endlocal