Basic - gregorymorrison/euler1 GitHub Wiki

BASIC (Beginner's All-purpose Symbolic Instruction Code) is the language that I cut my teeth on. Introduced way back in 1964, it was the first exposure that many of had to programming, because it was the native language of the first personal computers. Machines from Apple, Commodore, Radio Shack, Atari, IBM, etc. all had Basic built in and many even booted up into a Basic interpreter. Compared to today's standards, it was pretty crude. Early version required line numbers and didn't have support for procedures. Later versions like Visual Basic added limited OOP support. Here's a recursive version of Euler1 in QBasic:

' Euler1 in QBasic

DECLARE FUNCTION Euler1 (n)
FUNCTION Euler1 (n)
    IF n < 3 THEN
        Euler1 = 0
    ELSE IF n MOD 3 = 0 OR n MOD 5 = 0 THEN
        Euler1 = n + Euler1(n - 1)
    ELSE
        Euler1 = Euler1(n - 1)
    END IF
END FUNCTION

PRINT Euler1(999)

Notice there's no declared return variable - it's implicitly the same as the function name. Here's an iterative version of the same:

' Euler1 in QBasic

DECLARE FUNCTION Euler1 (n)
FUNCTION Euler1 (n)
    result = 0
    FOR i% = 1 TO n
        IF i% MOD 3 = 0 OR i% MOD 5 = 0 THEN
            result = result + i%
        END IF
    NEXT i%
    Euler1 = result
END FUNCTION

PRINT Euler1(999)

And here is the same code, written in the BBC Basic dialect:

REM Euler1 in BBC Basic

PRINT Euler1(999)
QUIT

DEF Euler1(n)
    LOCAL i, result
    result = 0
    FOR i = 1 TO n
        IF i MOD 3 = 0 OR i MOD 5 = 0 THEN
            result = result + i
        ENDIF
    NEXT i
    =result

This example illustrates the effect of the interpreter on the language's design. Execution starts at the top and works its way down. The main body of the program must be at the top because BBC Basic's runtime isn't even smart enough to predefine functions - it only defines and executes them as needed. Moving 'DEF Euler1(n)' to the top merely confuses it. Likewise, I couldn't get recursion to work in BBC Basic, though the runtime supposedly supports it.

To execute the QBasic code, I used the cool JavaScript-based web interpreter, repl.it. Just type your code in the box and click the arrow to run. I'm embarrassed to admit that it took me a little bit to realize why my execution attempts would only work the first time. It's because it's a REPL, duh! The very first line of code is a declaration, and the REPL announces that it's already defined and then quits. Fair enough...

To run BBC Basic code, I used Brandy. Yum-install and then execute, including a quit flag to exit the interpreter when finished:

$ brandy -quit euler1.bas
    233168