Руководство small basic

User guide

SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for everyday calculations, scripts and prototypes. SmallBASIC includes trigonometric, matrices and algebra functions, a built in IDE, a powerful string library, system, sound, and graphic commands along with structured programming syntax.

Contents

  • Constants and Variables
  • Variable names
  • About the dollar-symbol
  • Integers
  • Reals
  • Strings
  • Constants
  • System Variables
  • Operators
  • Special Characters
  • Statement OPTION keyword
  • Run-Time
  • Statement OPTION BASE
  • Statement OPTION MATCH
  • Compile-Time
  • Statement OPTION PREDEF
  • Meta-commands
  • The operator LIKE
  • Single-line Functions
  • Units
  • The pseudo-operators
  • The USE keyword
  • The DO keyword
  • Using LOCAL variables
  • Loops and variables

Constants and Variables

  • All user variables (include arrays) are ‘Variant’. That means the data-type is invisible to user.
  • Arrays are always dynamic, even if you had declared their size, with dynamic size and type of elements.

However, SmallBASIC uses, internally, 4 data-types

  • Integer (32bit)
  • Real (64bit)
  • String (<32KB on 16bit / 2GB on 32bit)
  • Array (~2970 elements on 16bit / ~50M elements on 32bit)

Conversions between those types are performed internally. In any case there are functions for the user to do it manually.

Variable names

Variable names can use any alphanumeric characters, extended characters (ASCII codes 128-255 for non-English languages) the symbol ’_‘, and the symbol ’$‘. The first character of the name cannot be a digit nor ’$’.

About the dollar-symbol

The symbol ‘$’ is supported for compatibility. Since in SmallBASIC there are no data-types its use is meaningless.

The dollar in function names will be ignored.

The dollar in variable names will be count as part of the name (that means v and v$ are two different variables). It can be used only as the last character of the name, and only one allowed.

The dollar in system variables names will be ignore it (that means COMMAND and COMMAND$ is the same)

Example of variable names:

abc, a_c, _bc, ab2c, abc$ -> valid names
1cd, a$b, $abc            -> invalid names

Integers

This is the default data type. You can declare integers in decimal, hexadecimal, octal and binary form.

x = 256   '
x = 0x100 ' Hexadecimal form 1
x = &h100 ' Hexadecimal form 2
x = 0o400 ' Octal form 1
x = &o400 ' Octal form 2
x = 0b111 ' Binary form 1
x = &b111 ' Binary form 2

Reals

Any number which out-bounds the limits or an ‘integer’ or had decimal digits will be converted automatically to real.

x = .25
x = 1.2

Reals can be also written by using scientific notation. 1E+2 or 1E-+2, 5E–2, 2.6E-0.25, etc

Strings

Strings may be appended to one another using the + operator.

b = "Hello, " + "world!"
b = """This is
a string
over several lines
with line breaks"""

Constants

Constant variables can be declared by using the keyword CONST.

CONST my_pi = 3.14

System Variables

System variables, are constant variables for the programmer. Those variables get values or modified at run-time by the SB’s subsystem.

  • SBVER SmallBASIC Version (0xAABBCC)
  • PI 3.14..
  • XMAX Graphics display, maximum x (width-1)
  • YMAX Graphics display, maximum y (height-1) value
  • CWD Current Working Directory
  • HOME User’s home directory
  • COMMAND Command-line parameters
  • TRUE The value 1
  • FALSE The value 0

Operators

Sorted by priority

( ) Parenthesis
+, — Unary
~ bitwise NOT
NOT or ! Logical NOT (NOT false = true)
^ Exponentiation
*, /, Multiplication, Division, Integer Division
% or MOD Reminder (QB compatible: a=int(a), b=int(b), a-b*(a/b))
MDL Modulus (a%b+b*(sgn(a)<>sgn(b)))
+, — Addition/Concatenation, Subtraction
= Equal
<> or != Not Equal
>, < Less Than, Greater Than
=>, =< Less or Equal, Greater or Equal
>=, <= Less or Equal, Greater or Equal
IN belongs to … (see “The IN operator”)
LIKE Regular expression match (see “The LIKE operator”)
AND or && Logical AND
OR or Logical OR
BAND or & bitwise AND
BOR or bitwise OR
EQV bitwise EQV
IMP bitwise IMP
XOR bitwise XOR
NAND bitwise NAND
NOR bitwise NOR
XNOR bitwise XNOR

Special Characters

&h or 0x Prefix for hexadecimal constant (0x1F, &h3C)
&o or 0o Prefix for octal constant (0o33, &o33)
&b or 0b Prefix for binary constant (0b1010, &b1110)
[,;] Array definition (function ARRAY()) ($1)
<< Appends to an array (command APPEND) ($1)
++ Increase a value by 1 (x = x + 1) ($1)
Decrease a value by 1 (x = x — 1) ($1)
p= Another LET macro (x = x p …). Where p any character of -+/*^%&
: Separates commands typed on the same line
& Join code lines (if its the last character of the line). The result line its must not exceed the max. line size.
# Meta-command (if its the first character of the line) or prefix for file handle
@ The ‘at’ symbol can by used instead of BYREF ($1)
Remarks

Pseudo operators. These operators are replaced by compiler with a command or an expression.

Statement OPTION keyword parameters

This special command is used to pass parameters to the SB-environment. There are two styles for that, the run-time (like BASE) which can change the value at run-time, and the compile-time (like PREDEF) which used only in compile-time and the value cannot be changed on run-time.

Run-Time

Statement OPTION BASE lower-bound

The OPTION BASE statement sets the lowest allowable subscript of arrays to lower-bound. The default is zero. The OPTION BASE statement can be used in any place in the source code but that is the wrong use of this except if we have a good reason. In most cases the OPTION BASE must declared at first lines of the program before any DIM declaration.

Statement OPTION MATCH PCRE [CASELESS]|SIMPLE

Sets as default matching algorithm to (P)erl-(C)ompatible (R)egular (E)xpressions library or back to simple one. Matching-algorithm is used in LIKE and FILES.

PRCE works only in systems with this library and it must be linked with. Also, there is no extra code on compiler which means that SB compiles the pattern every time it is used.

Compile-Time

Statement OPTION PREDEF parameter

Sets parameters of the compiler. Where parameter

  • QUIET Sets the quiet flag (-q option)

  • COMMAND cmdstr Sets the COMMAND$ string to var (useful for debug reasons)

  • GRMODE [widthxheight[xbpp]] Sets the graphics mode flag (-g option) or sets the preferred screen resolution. Example: (Clie HiRes)

    OPTION PREDEF GRMODE 320x320x16
  • TEXTMODE Sets the text mode flag (-g- option)

  • CSTR Sets as default string style the C-style special character encoding (‘’)

  • ANTIALIAS off : Disable anti-aliasing for drawing commands like CIRCEL or LINE

Meta-commands

#!…

Used by Unix to make source runs as a script executable

#sec: section-name

Used internally to store the section name. Sections names are used at limited OSes like PalmOS for multiple 32kB source code sections.

#inc: file

Used to include a SmallBASIC source file into the current BASIC code

#unit-path: path

Used to setup additional directories for searching for unit-files This meta does nothing more than to setting up the environment variable SB_UNIT_PATH. Directories on Unix must separated by ‘:’, and on DOS/Windows by ‘;’

Examples

#inc:"mylib.bas"
...
MyLibProc "Hi"
*Arrays and Matrices*
Define a 3x2 matrix
A = [11, 12; 21, 22; 31, 32]

That creates the array

The comma used to separate column items; the semi-colon used to separate rows. Values between columns can be omitted.

A = [ ; ; 1, 2 ; 3, 4, 5]

This creates the array

Supported operators: Add/sub:

B = [1, 2; 3, 4]: C = [5, 6; 7, 8]
A = B + C
C = A - B

Equal:

bool=(A=B)

Unary:

A2 = -A

Multiplication:

A = [1, 2; 3, 4]: B = [5 ; 6]
C = A * B
D = 0.8 * A

Inverse:

A = [ 1, -1, 1; 2, -1, 2; 3, 2, -1]
? INVERSE(A)

Gauss-Jordan:

? "Solve this:"
? "  5x - 2y + 3z = -2"
? " -2x + 7y + 5z =  7"
? "  3x + 5y + 6z =  9"
?
A = [ 5, -2, 3; -2, 7, 5; 3, 5, 6]
B = [ -2; 7; 9]
C = LinEqn(A, B)
? "[x;y;z] = "; C

There is a problem with 1 dimension arrays, because 1-dim arrays does not specify how SmallBASIC must see them.

DIM A(3)

or

And because this is not the same thing. (ex. for multiplication) So the default is columns DIM A(3) ’ or A(1,3)

For vertical arrays you must declare it as 2-dim arrays Nx1

DIM A(3,1)

Nested arrays are allowed

A = [[1,2] , [3,4]]
B = [1, 2, 3]
C = [4, 5]
B(2) = C
print B

This will be printed

[1, 2, [4, 5], 3]

You can access them by using a second (or third, etc) pair of parenthesis.

B(2)(1) = 16
print B(2)(1)

Result: 16

The operator IN

IN operator is used to compare if the left-value belongs to right-value.

' Using it with arrays
print 1 in [2,3]        :REM FALSE
print 1 in [1,2]        :REM TRUE
print "b" in ["a", "b", "c"] :REM TRUE
...
' Using it with strings
print "na" in "abcde"   :REM FALSE
print "cd" in "abcde"   :REM TRUE
...
' Using it with number (true only if left = right)
print 11 in 21          :REM FALSE
print 11 in 11          :REM TRUE
...
' special case
' auto-convert integers/reals
print 12 in "234567"    :REM FALSE
print 12 in "341256"    :REM TRUE

The operator LIKE

LIKE is a regular-expression operator. It is compares the left part of the expression with the pattern (right part). Since the original regular expression code is too big (for handhelds), I use only a subset of it, based on an excellent old stuff by J. Kercheval (match.c, public-domain, 1991). But there is an option to use PCRE (Perl-Compatible Regular Expression library) on systems that is supported (Linux); (see OPTION).

The same code is used for filenames (FILES(), DIRWALK) too. In the pattern string:

* matches any sequence of characters (zero or more)
? matches any character
[SET] matches any character in the specified set,
[!SET] or [^SET] matches any character not in the specified set.

A set is composed of characters or ranges; a range looks like character hyphen character (as in 0-9 or A-Z). [0-9a-zA-Z_] is the minimal set of characters allowed in the [..] pattern construct. To suppress the special syntactic significance of any of []*?!^-\', and match the character exactly, precede it with a’.

? "Hello" LIKE "*[oO]" : REM TRUE
? "Hello" LIKE "He??o" : REM TRUE
? "Hello" LIKE "hello" : REM FALSE
? "Hello" LIKE "[Hh]*" : REM TRUE

The pseudo-operator <<

This operator can be used to append elements to an array.

A << 1
A << 2
A << 3
? A(1)

Syntax of procedure (SUB) statements

 SUB name [([BYREF] par1 [, ...[BYREF] parN)]]
  [LOCAL var[, var[, ...]]]
  [EXIT SUB]
  ...
END

Syntax of function (FUNC) statements

FUNC name[([BYREF] par1 [, ...[BYREF] parN)]]
  [LOCAL var[, var[, ...]]]
  [EXIT FUNC]
  ...
  name=return-value
END

On functions you must use the function’s name to return the value. That is, the function-name acts like a variable and it is the function’s returned value. The parameters are ‘by value’ by default. Passing parameters by value means the executor makes a copy of the parameter to stack. The value in caller’s code will not be changed.

Use BYREF keyword for passing parameters ‘by reference’. Passing parameters by reference means the executor push the pointer of variable into the stack. The value in caller’s code will be the changed.

' Passing 'x' by value
SUB F(x)
  x=1
END
x=2
F x
? x:REM displays 2
> ' Passing 'x' by reference
SUB F(BYREF x)
  x=1
END
x=2
F x
? x:REM displays 1

You can use the symbol @ instead of BYREF. There is no difference between @ and BYREF.

 SUB F(@@x)
  x=1
END

On a multi-section (PalmOS) applications sub/funcs needs declaration on the main section.

sec:Main
declare func f(x)
#sec:another section
func f(x)
...
end

Use the LOCAL keyword for local variables. LOCAL creates variables (dynamic) at routine’s code.

SUB MYPROC
  LOCAL N:REM LOCAL VAR
  N=2
  ? N:REM displays 2
END
N=1:REM GLOBAL VAR
MYPROC
? N:REM displays 1

You can send arrays as parameters. When using arrays as parameters its better to use them as BYREF; otherwise their data will be duplicated in memory space.

SUB FBR(BYREF tbl)
  ? FRE(0)
  ...
END
SUB FBV(tbl)
  ? FRE(0)
  ...
END
' MAIN
DIM dt(128)
...
? FRE(0)
FBR dt
? FRE(0)
FBV dt
? FRE(0)
Passing & returning arrays, using local arrays.
func fill(a)
  local b, i
  dim b(16)
  for i=0 to 16
    b(i)=16-a(i)
  next
  fill=b
end
DIM v()
v=fill(v)

Single-line Functions

There is also an alternative FUNC DEF syntax (single-line functions). This is actually a macro for compatibility with the BASIC’s DEF FN command, but quite useful.

FUNC name[(par1[,...])] = expression
or
DEF name[(par1[,...])] = expression
DEF MySin(x) = SIN(x)
? MySin(pi/2)

Nested procedures and functions

One nice feature, are the nested procedures/functions. The nested procedures/functions are visible only inside the “parent” procedure/function. There is no way to access a global procedure with the same name of a local.

FUNC f(x)
    Rem Function: F/F1()
    FUNC f1(x)
        Rem Function: F/F1/F2()
        FUNC f2(x)
            f2=cos(x)
        END
        f1 = f2(x)/4
    END
    Rem Function: F/F3()
    FUNC f3
        f3=f1(pi/2)
    END
REM
? f1(pi) : REM OK
? f2(pi) : REM ERROR
f = x + f1(pi) + f3 : REM OK
END

Units

Units are a set of procedures, functions and/or variables that can be used by another SB program or SB unit. The main section of the unit (commands out of procedure or function bodies) is the initialization code.

A unit declared by the use of UNIT keyword.

UNIT MyUnit

The functions, procedure or variables which we want to be visible to another programs must be declared with the EXPORT keyword.

UNIT MyUnit
EXPORT MyF
...
FUNC MyF(x)
...
END

Keep file-name and unit-name the same. That helps the SB to automatically recompile the required units when it is needed. To link a program with a unit we use the IMPORT keyword.

IMPORT MyUnit

To access a member of a unit we must use the unit-name, a point and the name of the member.

IMPORT MyUnit
...
PRINT MyUnit.MyF(1/1.6)
Full example:
file my_unit.bas:
UNIT MyUnit
EXPORT F, V
REM a shared function
FUNC F(x)
    F = x*x
END
REM a non-shared function
FUNC I(x)
    I = x+x
END
REM Initialization code
V="I am a shared variable"
L="I am invisible to the application"
PRINT "Unit 'MyUnit' initialized :)"
file my_app.bas:
IMPORT MyUnit
PRINT MyUnit.V
PRINT MyUnit.F(2)

The pseudo-operators

++/–/p= The ++ and – operators are used to increase or decrease the value of a variable by 1.

x = 4
x ++ : REM x <- x + 1 = 5
x -- : REM x <- x - 1 = 4

The generic p= operators are used as in C Where p any character of -+/*^%&|

x += 4 : REM x <- x + 4
x *= 4 : REM x <- x * 4

All these pseudo-operators are not allowed inside of expressions

y = x ++ ' ERROR
z = (y+=4)+5 ' ALSO ERROR

The USE keyword

This keyword is used on specific commands to passing a user-defined expression.

SPLIT s," ",v USE TRIM(x)

In that example, every element of V() will be ‘trimmed’. Use the x variable to specify the parameter of the expression. If the expression needs more parameter, you can use also the names y and z

The DO keyword

This keyword is used to declare single-line commands. It can be used with WHILE and FOR-family commands.

FOR f IN files("*.txt") DO PRINT f
...
WHILE i < 4 DO i ++

Also, it can be used by IF command (instead of THEN), but is not suggested.

Using LOCAL variables

When a variable is not declared it is by default a global variable. A usual problem is that name may be used again in a function or procedure.

FUNC F(x)
  FOR i=1 TO 6
    ...
  NEXT
END
FOR i=1 TO 10
  PRINT F(i)
NEXT

In this example, the result is a real mess, because the var i of the main loop will always (except the first time) have the value 6! This problem can be solved if we use the LOCAL keyword to declare the var in the function body.

FUNC F(x)
  LOCAL i
  FOR i=1 TO 6
    ...
  NEXT
END
FOR i=1 TO 10
  PRINT F(i)
NEXT

It is good to declare all local variables on the top of the function. For compatibility reasons, the func./proc. variables are not declared as ‘local’ by default. That it is WRONG but as I said … compatibility.

Loops and variables

When we write loops it is much better to initialize the counters on the top of the loop instead of the top of the program or nowhere.

i = 0
REPEAT
  ...
  i = i + 1
UNTIL i > 10

p.. Initializing variables at the top of the loop can make code more readable.

Loops and expressions

FOR-like (loops) commands evaluate both the "destination" and the exit-expression every time.
FOR i=0 TO LEN(FILES("*.txt"))-1
    PRINT i
NEXT

In that example the ‘destination’ is the LEN(FILES(«*.txt»))-1 For each value of i the destination will be evaluated. That is WRONG but it is supported by BASIC and many other languages. So, it is much better to be rewritten as

idest=LEN(FILES("*.txt"))-1
FOR i=0 TO idest
    PRINT i
NEXT

Of course, it is much faster too.

Введение в Small Basic.pdf

3 мая 2014 г.

1,6 МБ

Виртуальные коды клавиш для LastKey.doc

8 мая 2014 г.

238 КБ

Занимательные уроки с компьютером (Рубанцев).pdf

3 мая 2014 г.

35,9 МБ

Команды SB описание ru (Папа Alex_2000).doc

8 мая 2014 г.

568 КБ

Копия Занимательные уроки с компьютером (Рубанцев).pdf

25 нояб. 2022 г.

35,9 МБ

Краткое введение в язык SmallBasic (Папа Alex_2000).doc

8 мая 2014 г.

772 КБ

О массивах (дополнение).doc

8 мая 2014 г.

210 КБ

Программирование для студентов и школьников на примере Small Basic (Ахметов Ильдар).pdf

8 мая 2014 г.

4,9 МБ

Таблица кодов цветов в HTML, RGB и буквенное написание.doc

8 мая 2014 г.

679 КБ

FC — описание библиотеки (ru).doc

8 мая 2014 г.

362 КБ

SmallBasic для начинающих (Культин,Цой).pdf

8 мая 2014 г.

5,7 МБ

Small Basic >
Small Basic Books >
The Developer’s Reference
Guide to Small Basic > 1. Introducing Small Basic

Preview

In this first chapter, we will do an overview of how to write a program using Small Basic. You’ll get a brief history of Small Basic and look into use of the Small Basic development environment.

Introducing Guide to Small Basic

In these notes, we provide a thorough overview of the Microsoft Small Basic programming environment. We review the language of Small Basic and the objects used by Small Basic. We also cover many advanced topics. Along the way, we will build many Small Basic
example programs to illustrate the skills learned. You can use many of these code “snippets” in programs and applications you build. All Small Basic code is included with the notes.

As a first step to this overview, we will review Small Basic and its development environment in the remainder of this chapter. Then, we provide a review of the Small Basic programming language in Chapter 2. Beginning with Chapter 3, we cover many of the
objects included as part of Small Basic. With each chapter, objects will be summarized and several example programs will be built to show how Small Basic can be used. The notes end with chapters on advanced topics such as debugging, graphics, animation, sharing
programs on the Internet, graduating programs to Microsoft Visual Basic and building libraries you can use in Small Basic.

The Developer’s Reference Guide

This chapter is adapted from the book The Developer’s Reference Guide To Microsoft Small Basic by Philip Conrod and Lou Tylee.

To purchase this book in its entirety, please see the
Computer Science For Kids web site.

 

Requirements for Guide to Small Basic

Before starting, let’s examine what you need to successfully build the programs included with
The Developer’s Reference Guide to Small Basic. As far as computer skills, you should be comfortable working within the Windows environment. You should know how to run programs, find and create folders, and move and resize windows.

As far as programming skills, we assume you have had some exposure to computer programming using some language. If that language is
Small Basic, great!! We offer two beginning Small Basic tutorials that could help you gain that exposure (see our website for details). But, if you’ve ever programmed in any language (Visual Basic, C, C++, C#, Java, J#, Ada, even FORTRAN),
you should be able to follow what’s going on.

Regarding software requirements, to use Small Basic, you must be using Windows 7, 2000, Windows XP, Windows NT or Windows Vista. These notes and all programs are developed using Windows Vista and Version 0.9 of Small Basic. And, of course, you need to have
the Small Basic product installed on your computer. It is available for free download from Microsoft. Follow this link for complete instructions for downloading and installing Small Basic on your computer:

http://www.smallbasic.com/

Introducing Small Basic

In the late 1970’s and early 1980’s, it seems there were computers everywhere with names like Commodore 64, Texas Instruments 99/4A, Atari 400, Coleco Adam, Timex Sinclair and the IBM PC-Jr. Stores like Sears, JC Penneys and even K Mart sold computers. One
thing these machines had in common was that they were all programmed in some version of Microsoft’s BASIC. Each computer had its own fans and own magazines. Users would wait each month for the next issue of a magazine with BASIC programs you could type into
your computer and try at home.

This was a fun and exciting time for the beginning programmer, but the fun times ended with the introduction of the IBM-PC in the early 1980’s. Bigger and faster computers brought forth bigger languages and bigger development environments. These new languages
were expensive to acquire and difficult for the beginning programmer to grasp.

Which brings us to Small Basic, which I would call a relative of the early, original BASIC language. The development of Small Basic is an attempt to rekindle the exciting days when just about anyone could sit down at a computer and write
a simple program using the BASIC language. Those of you who wrote programs on those old “toy” computers will recognize the simplicity of the Small Basic language and the ease of its use. And, you will also notice Small Basic is a great environment for writing
and testing code, something missing in the early 1980’s. For those of you new to programming, I hope you can feel the excitement we old timers once had. For the old timers, I hope you rekindle your programming skills with this new product.

Small Basic possesses many features of more powerful (and more expensive) programming languages:

  • Easy-to-use, Integrated Development Environment (IDE)
  • Response to mouse and keyboard actions
  • Button and text box controls
  • Full array of mathematical, string handling, and graphics functions
  • Can easily work with arrays
  • Sequential file support

Starting Small Basic

We assume you have Small Basic installed and operational on your computer. Once installed, to start Small Basic:

  • Click on the Start button on the Windows task bar
  • Select Programs, then Small Basic
  • Click on Microsoft Small Basic

(Some of the headings given here may differ slightly on your computer, but you should have no trouble finding the correct ones.) The Small Basic program should start.

After installation and trying to start, you may see an error message that announces Small Basic cannot be started. If this occurs, try downloading and installing the latest version of the Microsoft .NET framework at:

http://msdn.microsoft.com/en-us/netframework/aa569263.aspx

This contains some files that Small Basic needs to operate and such files may not be on your computer.

Upon starting, my screen shows:

This window displays the Small Basic Development Environment. There are many areas of interest on the screen. At the top of the window is the
Title Bar. The title bar gives us information about what program we’re using and what Small Basic program we are working with. Below the title bar is a
Toolbar. Here, little buttons with pictures allow us to control Small Basic.

In the middle of the screen is the Editor. This is where we will write our Small Basic programs. To the right is a
Help area. Small Basic has great help features when writing programs. This area will display hints and tips while we write code.

Running a Small Basic Program

Let’s write our first Small Basic program. When you start, a new editor window appears. You can also get a new editor window by clicking the
New toolbar button. Type these two lines in the editor window:

TextWindow.Title = "Hello Program" TextWindow.WriteLine("This is the first line of the program.")

The editor window should look like this:

Notice as you started typing the first line, this popped-up:

Small Basic has “intellisense” and uses this to make typing suggestions. You can just keep typing or accept its suggestion by scrolling through the pop-up list and pressing the
Enter key.

Also, notice this appeared in the help area:

Once you typed TextWindow, the help feature displayed all it knows about the
TextWindow to help you in your programming.

The TextWindow is a Small Basic object. It displays text output. The object has
properties, methods and events. There are many objects in Small Basic. They will be covered in detail in individual chapters of these notes.

Let’s Run the program. Simply click the Run button on the toolbar to see:

This is the text window displaying the program output. I have resized the window. To stop the program, click the
X in the upper right corner of the window.

That’s all there is to writing a Small Basic program. Type the code in the editor window. Click the
Run button to run the code. We will learn how to use a lot of Small Basic code as we work through these notes. Chapter 2 reviews most elements of the Small Basic language.

Other useful toolbar buttons are:

Open – Open a previously saved Small Basic program
Save – Save a Small Basic program
Save As – Save a Small Basic program with a different name

We suggest saving each Small Basic program in its own folder.

When you Save and Run a Small Basic program, four files are created. If you name your program
MyProgram, the corresponding files in the program folder are:

MyProgram.sb The codethat appears in the editor of Small Basic
MyProgram.exe A ‘compiled’ version of the code.
MyProgram.pdb A database file with information needed by your program
SmallBasicLibrary.dll The Small Basic run-time library. It contains files that help your program run.

Do not modify any of these files outside the Small Basic environment.

There are also the Cut, Copy, Paste,
Undo, and Redo buttons for common editing tasks. They work just like the corresponding buttons in a word processing program. Learn to use these – they will save you lots of time typing code.

Lastly, there are other buttons on the toolbar we will discuss in later chapters:

Import – Import a program from the Small Basic code repository
Publish – Publish a program to the Small Basic code repository
Graduate – Convert a Small Basic program to Visual Basic Express

Chapter Review

This completes our overview of the Small Basic environment and a brief demonstration of how to write a Small Basic program. If you’ve used Small Basic before, this material should be familiar. If you’ve programmed with other languages, you should have a
fairly clear understanding of what’s going on.

After completing this chapter, you should understand:

  • A little of the history of Small Basic.
  • The various parts of the Small Basic integrated development environment.
  • The utility of “intellisense” and the Small Basic help panel.
  • How to write code using the code editor.
  • How to run a Small Basic program.

Next, let’s review the language of Small Basic.

Next Chapter
> >

Excerpt © Copyright 2010-2013 By Kidware Software LLC All Rights Reserved. Computer Science For Kids, the Computer Science For Kids logo, and related trade dress are trademarks or registered trademarks of Kidware Software LLC.
Philip Conrod & Lou Tylee have co-authored dozens of books and tutorials for beginning Microsoft Basic, Small Basic, Visual Basic, and Visual C# developers of all ages for over 25 years. 

Никита Культин Лариса Цой

Санкт-Петербург «БХВ-Петербург»

2011

УДК

681.3.06

ББК

32.973.26-018.2

К90

Культин, Н.

К90

Small Basic для начинающих / Н. Культин, Л. Цой. — СПб.:

БХВ-Петербург, 2011. — 256 с.: ил. + Дистрибутив (на DVD)

ISBN 978-5-9775-0664-9

В доступной форме изложены основы теории программирова-

ния, приведено описание современного языка программирования для

начинающих — Microsoft Small Basic и рассмотрен процесс создания

программы от составления алгоритма до отладки. Показано, как за-

писать инструкции программы,

использовать инструкции выбора

и циклов, ввести исходные данные и вывести результат работы про-

граммы на экран, работать с массивами, файлами, графикой и др.

На DVD содержится дистрибутив среды разработки Small Basic,

примеры, рассмотренные в книге, и справочная информация.

Для начинающих программистов

УДК 681.3.06

ББК 32.973.26-018.2

Группа подготовки издания:

Главный редактор

Екатерина Кондукова

Зам. главного редактора

Игорь Шишигин

Зав. редакцией

Григорий Добин

Редактор

Анна Кузьмина

Компьютерная верстка

Натальи Караваевой

Корректор

Виктория Пиотровская

Дизайн серии и

Елены Беляевой

оформление обложки

Зав. производством

Николай Тверских

Лицензия ИД № 02429 от 24.07.00. Подписано в печать 08.11.10. Формат 60 901/16. Печать офсетная. Усл. печ. л. 16.

Тираж 2000 экз. Заказ № «БХВ-Петербург», 190005, Санкт-Петербург, Измайловский пр., 29.

Санитарно-эпидемиологическое заключение на продукцию № 77.99.60.953.Д.005770.05.09 от 26.05.2009 г. выдано Федеральной службой

по надзору в сфере защиты прав потребителей и благополучия человека.

Отпечатано с готовых диапозитивов в ГУП «Типография «Наука»

199034, Санкт-Петербург, 9 линия, 12

ISBN 978-5-9775-0664-9

©Культин Н., Цой Л., 2010

©Оформление, издательство «БХВ-Петербург», 2010

Оглавление

Предисловие …………………………………………………………………………..

1

Small Basic — что это?……………………………………………………………..

1

Об этой книге …………………………………………………………………………..

2

Глава 1. Microsoft Small Basic ………………………………………………..

3

Установка ………………………………………………………………………………..

5

Запуск………………………………………………………………………………………

5

Первый взгляд………………………………………………………………………….

7

Глава 2. Первая программа………………………………………………….

11

Набор текста программы ………………………………………………………..

16

Сохранение программы ………………………………………………………….

17

Запуск программы ………………………………………………………………….

19

Ошибки в программе………………………………………………………………

20

Завершение работы…………………………………………………………………

22

Внесение изменений в программу …………………………………………..

23

Запуск программы из Windows ……………………………………………….

25

Установка программы на другой компьютер …………………………..

26

Глава 3. Введение в программирование ………………………………

27

Алгоритм и программа……………………………………………………………

29

Этапы разработки программы…………………………………………………

30

Алгоритм ……………………………………………………………………………….

32

Алгоритмические структуры…………………………………………………..

37

Следование …………………………………………………………………………

37

Выбор …………………………………………………………………………………

38

Цикл……………………………………………………………………………………

40

IV

Оглавление

Стиль программирования ……………………………………………………….

42

Программа ……………………………………………………………………………..

45

Комментарии………………………………………………………………………….

45

Типы данных и переменные ……………………………………………………

46

Константы………………………………………………………………………………

48

Числовые константы……………………………………………………………

48

Строковые константы………………………………………………………….

48

Инструкция присваивания ………………………………………………………

49

Выражение………………………………………………………………………….

50

Понятие функции……………………………………………………………………

52

Ввод и вывод………………………………………………………………………….

53

Вывод информации на экран ……………………………………………….

53

Ввод данных ……………………………………………………………………….

57

Глава 4. Инструкции управления ………………………………………..

61

Условие………………………………………………………………………………….

63

Операторы сравнения ………………………………………………………….

63

Логические операторы…………………………………………………………

66

Инструкция If …………………………………………………………………………

68

Выбор …………………………………………………………………………………

68

Глава 5. Циклы …………………………………………………………………….

79

Инструкция For………………………………………………………………………

82

Инструкция While …………………………………………………………………..

86

Глава 6. Массивы …………………………………………………………………

89

Доступ к элементу массива……………………………………………………..

92

Ввод массива………………………………………………………………………….

93

Вывод массива ……………………………………………………………………….

95

Поиск минимального элемента ……………………………………………….

97

Сортировка массива ……………………………………………………………….

99

Сортировка методом прямого выбора ………………………………..

100

Сортировка методом «пузырька»………………………………………..

103

Поиск в массиве……………………………………………………………………

106

Метод перебора…………………………………………………………………

106

Бинарный поиск ………………………………………………………………..

109

Оглавление

V

Двумерные массивы ……………………………………………………………..

115

Ошибки при работе с массивами …………………………………………..

126

Глава 7. Подпрограмма………………………………………………………

129

Глава 8. Графика ………………………………………………………………..

141

Графическая поверхность……………………………………………………..

144

Графические примитивы……………………………………………………….

148

Точка ………………………………………………………………………………..

149

Линия………………………………………………………………………………..

149

Прямоугольник………………………………………………………………….

153

Эллипс, окружность и круг ………………………………………………..

156

Текст…………………………………………………………………………………

159

Иллюстрации………………………………………………………………………..

161

Анимация……………………………………………………………………………..

168

«Черепашья» графика ……………………………………………………………

175

Глава 9. Файлы …………………………………………………………………..

181

Чтение данных из файла ……………………………………………………….

185

Запись данных в файл …………………………………………………………..

189

Ошибки при работе с файлами………………………………………………

194

Глава 10. Примеры программ…………………………………………….

195

Экзаменатор …………………………………………………………………………

197

Диаграмма ……………………………………………………………………………

213

Игра «15»………………………………………………………………………………

219

Игра «Парные картинки» ………………………………………………………

232

Приложение. Описание DVD………………………………………………

241

Предметный указатель……………………………………………………….

246

Предисловие

Small Basic — что это?

В последнее время возрос интерес к программированию. Это связано с развитием и внедрением в повседневную жизнь информа- ционно-коммуникационных технологий. Если кто-то имеет дело с компьютером, то рано или поздно у него возникает желание, а иногда и необходимость, программировать.

Среди пользователей персональных компьютеров в настоящее время наиболее популярна операционная система Windows, и естественно, что тот, кто хочет программировать, стремится писать программы «под Windows».

И здесь возникает проблема: современные системы программи-

рования, такие как Microsoft Visual Basic, Delphi и, тем более, Microsoft Visual C++, ориентированы на профессиональную разработку и предполагают наличие у пользователя знаний и начального опыта в области программирования. Другими словами, они не подходят для целей обучения программированию. Как быть? Конечно, можно освоить базовые концепции, изучив язык программирования Pascal. Однако в этом случае придется выполнять упражнения и решать задачи в явно устаревшей, ориентированной на работу в операционной системе DOS среде разработки Turbo Pascal, столкнуться с массой проблем при ее использовании в современных операционных системах семейства Windows (начиная с проблемы переключения на русский алфавит при наборе текста программы).

Очевидно, осознав проблему отсутствия современной среды разработки, ориентированной на начинающих, Microsoft предложи-

ла свое решение — Microsoft Small Basic.

Как показал опыт, полученный в процессе написания этой книги, Microsoft Small Basic, несмотря на то, что он «маленький», вполне приличная (посмотрите программы, приведенные в главе 10) и, что важно, доступная для начинающих среда разработки. Она позволяет изучить базовые концепции программирования, алгоритмические структуры, инструкции управления ходом выполнения программы, циклы, научиться работать с массивами, файлами и графикой. В Microsoft Small Basic в качестве языка программирования используется диалект языка Basic, что позволяет в дальнейшем без особых проблем перейти на следующий уровень — начать работать в Microsoft Visual Basic.

Об этой книге

Книга, которую вы держите в руках, — это не описание языка программирования или среды разработки Microsoft Small Basic. Это руководство по программированию для начинающих. В нем рассмотрена вся цепочка, весь процесс создания программы: от разработки алгоритма и составления программы до отладки и переноса готовой программы на другой компьютер.

Цель этой книги — научить основам программирования: использовать операторы выбора, циклов, работать с массивами и файлами.

Чтобы научиться программировать, надо программировать, решать конкретные задачи. Поэтому, чтобы получить максимальную пользу от книги, вы должны работать с ней активно. Не занимайтесь просто чтением примеров, реализуйте их с помощью вашего компьютера. Не бойтесь экспериментировать — вносите изменения в программы. Чем больше вы сделаете самостоятельно, тем большему вы научитесь!

Понравилась статья? Поделить с друзьями:
  • Спазмалгон таблетки инструкция по применению показания к применению взрослым
  • Колонка sony srs xb31 инструкция по применению
  • Мбрр руководству по регулированию прямых иностранных инвестиций мбрр
  • Обозначение документов руководства по эксплуатации
  • Стимбифид плюс инструкция по применению цена отзывы аналоги таблетки взрослым