[home] Anguilla Library Computer Club
Resources

BASIC Lesson #3: Trees of Information

This lesson is the third part of a series on the BASIC programming language.

Activity: The "Guess an Animal" Program

If there is plenty of time, type in the program below and save it under your name by pressing Alt-F for the File menu list and then A for Save As. If time is short, use Alt-F O to open the pre-typed program in \lcc\basic03.bas. When you are ready to try running the program, press F5 (function key #5).

REM The computer guesses your animal and learns new animals.

REM We store questions and animals in the animals() array.
DIM animals(100) AS STRING

REM The arrays ifyes(), ifno() store numbers for next two possible questions.
REM Note that qbasic initializes arrays of numbers to 0s.
DIM ifyes(100)
DIM ifno(100)

LET animals(0) = "goldfish"
nextfree = 1

REM  Get user to think of a new animal.
90   current = 0
     PRINT "Hit ENTER when you are thinking of a new animal.";
     INPUT A$

REM  As long as this is not an animal, loop around asking questions.
100  IF (ifyes(current) = 0) GOTO 200
     PRINT animals(current); "? (y/n)"
     INPUT A$
    
     IF (A$ = "y") THEN
              current = ifyes(current)
         ELSE current = ifno(current)
     END IF
     GOTO 100

REM No more questions, so guess name of animal.
200 PRINT "Is it a "; animals(current); "? (y/n)";
    INPUT A$
    IF (A$ = "n") GOTO 300
    PRINT "I got it!"
    GOTO 90

REM  Learn a new animal.  Replace wrong animal with new question.
300  PRINT "You were thinking of an animal I don't know!"
     PRINT "What is your animal? ";
     INPUT newanimal$
     PRINT "What general question could I have asked to tell a ";
     PRINT newanimal$; " from a "; animals(current)
     INPUT question$
       
     animals(nextfree) = animals(current)
     animals(nextfree + 1) = newanimal$
     animals(current) = question$

     PRINT "And for a "; newanimal$; " the answer would be? (y/n)";
     INPUT answer$
     IF (answer$ = "y") THEN
         ifyes(current) = nextfree + 1
         ifno(current) = nextfree
     ELSE
         ifyes(current) = nextfree
         ifno(current) = nextfree + 1
     END IF

     nextfree = nextfree + 2
     GOTO 90