Jump to content

Programming Fundamentals/Loops/BASIC

From Wikiversity

loops.bas

[edit | edit source]
' This program demonstrates While, Do, and For loop counting using 
' user-designated start, stop, and increment values.
'
' References:
'     https://en.wikibooks.org/wiki/BASIC_Programming

DECLARE SUB Main()
DECLARE FUNCTION GetValue(Name$)
DECLARE SUB WhileLoop(Start, Finish, Increment)
DECLARE SUB DoLoop(Start, Finish, Increment)
DECLARE SUB ForLoop(Start, Finish, Increment)

Main

SUB Main()
    DIM Start
    DIM Finish
    DIM Increment

    Start = GetValue("starting")
    Finish = GetValue("ending")
    Increment = GetValue("increment")

    WhileLoop Start, Finish, Increment
    DoLoop Start, Finish, Increment
    ForLoop Start, Finish, Increment
END SUB


FUNCTION GetValue(Name$)
    DIM Value
    
    PRINT "Enter " + Name$ + " value:"
    INPUT Value
    
    GetValue = Value
END FUNCTION

SUB WhileLoop(Start, Finish, Increment)
    PRINT "While loop counting from " + STR$(Start) + " to ";
    PRINT STR$(Finish) + " by " + STR$(Increment) + ":"
    DIM Count
    
    Count = Start
    DO WHILE Count <= Finish
        PRINT Count
        Count = Count + Increment
    LOOP
END SUB

SUB DoLoop(Start, Finish, Increment)
    PRINT "Do loop counting from " + STR$(Start) + " to ";
    PRINT STR$(Finish) + " by " + STR$(Increment) + ":"
    DIM Count
    
    Count = Start
    DO
        PRINT Count
        Count = Count + Increment
    LOOP WHILE Count <= Finish
END SUB

SUB ForLoop(Start, Finish, Increment)
    PRINT "For loop counting from " + STR$(Start) + " to ";
    PRINT STR$(Finish) + " by " + STR$(Increment) + ":"
    DIM Count
    
    FOR Count = Start TO Finish STEP Increment
        PRINT Count
    NEXT Count
END SUB

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own BASIC compiler / interpreter / IDE.

See Also

[edit | edit source]