BASIC Programming/Printable version


BASIC Programming

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/BASIC_Programming

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Introduction

Introduction

edit


Normative BASIC

Normative BASIC

edit

The BASIC Programming Language has been standardized, firstly in the United States of America (USA) by the American National Standards Institute (ANSI), and later in Europe by the European Computer Manufacturers Association (ECMA), giving rise to the American National Standard (ANS) X3.60-1978 for Minimal BASIC and X3.113-1987 for Full BASIC by the former, and to the European Computer Manufacturers Association Standard 55 for Minimal BASIC in 1978 and Standard 116 for Full BASIC in 1986 by the latter.

The aim of the standards is to promote the interchangeability of BASIC programs among a variety of systems and through strict co-operation between both organizations it was possible to maintain full compatibility between the respective ANSI and ECMA standards.

The standards establish, among others:

  • the syntax of a program written in BASIC, and
  • the semantic rules for interpreting the meaning of a program written in BASIC.

Nowadays, only the ECMA standards are publicly available.

Minimal BASIC (ANS X3.60-1978, ECMA Standard 55)

edit

Character Set

edit

The set of allowable character is given by:

  • the set of capital letters from A to Z,
  • the set of digits from 0 to 9,
  • the set of symbols !, #, $, %, &, (, ), +, -, *, /, ^, ., ,, ;, :, <, =, >, _, ?, ', "
  • the space character

List of Reserved Keywords

edit

Reserved keywords in Minimal BASIC are (26 in total):

  1. BASE
  2. DATA
  3. DEF
  4. DIM
  5. END
  6. FOR
  7. GO
  8. GOSUB
  9. GOTO
  10. IF
  11. INPUT
  12. LET
  13. NEXT
  14. ON
  15. OPTION
  16. PRINT
  17. RANDOMIZE
  18. READ
  19. REM
  20. RESTORE
  21. RETURN
  22. STEP
  23. STOP
  24. SUB
  25. THEN
  26. TO

Its meaning will be explained within the next sections.

Convention for the Name of Variables

edit

Variables are used in BASIC to hold either character strings or numeric values, the latter being either of scalar or vectorial nature.

In the case of variables for character strings, each variable name is composed of a single letter between A - Z and the dollar sign $. So, A$, B$, ..., Z$ are all valid variable names for character strings, while A# or Z% are not.

In the case of variables for numeric scalar values, each variable name is composed of a single letter between A - Z and an optional digit. So, A, B, C1, D2, etc., are valid variable names for scalar values, while A11, B22, etc., are not.

In the case of variables for numeric vectorial values, each variable name is composed of a single letter between A - Z and either a number or two, separated by a comma, enclosed within parentheses for a one or a two dimensional array. So, A(1), B(2), C(1,1), D(2,2), etc., are valid variable names for vectorial values.

This convention makes the explicit declaration of variables not necessary in BASIC, since a dollar sign serves to distinguish a character string from a numeric value, and the presence of subscripts distinguishes a vectorial from a scalar variable.

Character Strings and Numeric Constants

edit

Character strings are defined by any combination of characters from the allowable character set written within double quotation marks, the length of any character string being limited to 18 characters (with the exception of character strings in a print or remark-statement, to be seen later, which can be as long as line numbers and the line length limit permit). So, "", " ", "1 2 3 4 5 6 7 8 9", "A B C D E F G H I", "! # $ % & ... ' ", etc., are allowable character strings, while "1 2 3 4 5 6 7 8 9 0", "A B C D E F G H I J", "! # $ % & ( ) + - * / ^ . , ; : < = > _ ? ' ", etc., are not, since they exceed the 18-character limit.

Numeric constants denote scalar numeric values in a decimal representation in positional notation of a number. There are four general syntactic forms of optionally signed numeric constants:

  • implicit point representation (sd...d), like in the case of 1, 2, +1, -2, etc.,
  • explicit point unscaled representation (sd...drd...d), like in the case of 1.0, 2.0, +1.0, -2.0, etc.,
  • explicit point scaled representation (sd...drd...dEsd...d), like in the case of 1.0E1, 2.0E-1, +1.0E+1.0, -2.0E-2.0, etc.,
  • implicit point scaled representation (sd...dEsd...d), like in the case of 1.0E1, 2.0E-1, +1.0E+1, -2.0E-2, etc.,

where:

  • s is an optional sign (+ or -),
  • d is a decimal digit (0 - 9),
  • r is a period (.), and
  • E means 10 to the power.

Numeric constants can have any number of digits, although internally not less than six significant decimal digits and a range between 1E-38 and 1E+38.

Numeric constants whose magnitude is less than machine infinitesimal are replaced by zero, while constants whose magnitude are larger than machine infinity are replaced by machine infinity with the appropriate sign.

General Program Structure

edit

BASIC is a line-oriented language, in the sense that a BASIC program can be considered as a sequence of lines, the last of which is an end-line, and each of which contains a keyword. Moreover, each line begins with a unique line number, which serves as a label for the statement contained in that line.

So, in BASIC every program can be represented with the following Backus-Naur form (BNF):

  • program = block end-line
  • block = line / for-block
  • line = line-number statement
  • line-number = digit digit? digit? digit?
  • end-line = line-number end-statement
  • end-statement = END
  • statement = data-statement / def-statement / dimension-statement / gosub-statement / goto-statement / if-then-statement / input-statement / let-statement / on-goto-statement / option-statement / print-statement / randomize-statement / read-statement / remark-statement / restore-statement / return-statement / stop-statement

So, the following simple examples are valid examples of a program in BASIC:

  • a two-line program (just a remark-statement, which serves to document the program and produces no output, and an end-statement, which terminates the program):
10 REM "REMARK STATEMENT"
20 END
  • a three-line program (just a remark-statement, a print-statement, which prints a character string, and an end-statement):
10 REM "HELLO WORLD PROGRAM"
20 PRINT "HELLO, WORLD!"
30 END


Programs lines are executed in sequential order, starting with the first one, until:

  • some other action is dictated by a control statement, or
  • an exception condition occurs, which results in abnormal termination of the program, or
  • a stop-statement or end-statement is executed.

So, in the first example, the first line, 10 REM "REMARK STATEMENT", is composed of a non-control statement which produces no output or internal activity, passing then to the second line, 20 END, which is composed of a control statement, the end-statement, which ends the program.

In the second example, there exists an additional line between the remark and the end-statement lines, being composed of a print-statement, also a non-control statement, which prints a character string.

The value of the line-numbers are positive integers, with leading zeroes having no effect. So, 1, 01, 10, 010, etc., are all valid line-numbers. Normally, line-numbers are given as multiples of 5 or 10, e.g., 10, 20, 30, 40, etc., which allows for room in case an additional line must be inserted in between existing lines.

Additionally, lines can be up to 72-characters long, so leaving 4 characters for the line-number, and a blank space as a separator between the line-number and the keyword, leaves 67 printable characters left for the statement in a line.

Spaces may occur anywhere in a BASIC program without affecting the execution of that program and may be used to improve the readability of the program.

All keywords in a program can be preceded by at least one space and, if not at the end of a line, can also be followed by at least one space.

Spaces shall not appear:

  1. at the beginning of a line
  2. within line numbers
  3. within keywords
  4. within numeric constants
  5. within function or variable names
  6. within two-character relation symbols

Program Variables

edit

Variables in BASIC are associated with either numeric or string values and, in the case of numeric values, may be either simple variables or references to elements of one or two-dimensional arrays, which are then called subscripted or compound variables.

As stated before, simple numeric variables are named by a single capital letter followed by an optional single digit, while subscripted variables are named by a single capital letter followed by one or two numbers, separated in this last case by a comma, enclosed within parentheses.

String variables are also to be named by a single capital letter followed by a dollar sign.

At any instant in the execution of a program, a numeric variable is associated with a single numeric value and a string variable is associated with a single string value, the value associated with the variable possibly being changed by program statements in the course of program execution.

The length of a character string associated with a string variable can change during execution of the program from a length varying between 0 for the empty string to 18 characters.

Simple numeric variables and string variables are declared implicitly through their appearance in the program (also no type definitions are necessary, due to the given naming convention), although it is good programming practice to initialize or set them to meaningful values at the beginning of the program before their use in any statement.

A subscripted variable, on the other hand, refers to the element in the one or two-dimensional array selected by the value or values of the subscripts, being the subscripts integer values.

Unless explicitly declared in a dimension statement (to be seen later), subscripted variables are implicitly declared by their first appearance in a program, in which case the range of each subscript is to be understood from zero to ten, both inclusive, unless the presence of an option-statement indicates that the range is defined from one to ten, both also inclusive.

Caution must be paid, so that the same single letter is not used both for the name of a simple variable and a composed variable, nor for the name of both a one-dimensional and a two-dimensional array.

On the contrary, this restriction does not apply between a simple variable and a string variable, whose names may agree except for the dollar sign.

So, the following simple examples are valid examples of a program in BASIC:

  • the previous three-line program, with a somewhat different comment line and a new character string, which indicates the value of pi, being printed:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 PRINT "PI = 3.14159265"
30 END
  • a modified four-line program which makes use of a let-statement to assign the numeric constant 3.14159265 to the numeric variable P in the second line, and a print-statement with a string constant and a numeric variable as a comma-separated list of arguments in the third line:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET P = 3.14159265
30 PRINT "PI = ", P
40 END
  • a modified five-line program which, still making use of a let-statement to assign the numeric constant 3.14159265 to the numeric variable P in the second line, now also makes use of a let-statement to assign the character constant "PI = " to the string variable P$ in a third line -- the print-statement in the fourth line is now composed of the comma-separated list of arguments formed by the string variable and the numeric variable:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET P = 3.14159265
30 LET P$ = "PI = "
40 PRINT P$, P
50 END

Statements

edit

Up to now we have seen how to declare/initialize simple numeric variables and string variables in the course of a program by means of the let-statement and how to print them with the help of the print-statement.

It is sometimes desirable not only to print the value of a variable, let it be a numeric or a character one, but to introduce the value as input to the program in order to compute a numerical value or to print a message depending on the value of a condition. For those cases, one needs to make use of expressions, mathematical functions, and control statements, as we shall see in this section.

Input/Output, Mathematical Operators, Expressions

edit

Expressions are normally classified as numeric expressions or string expressions.

In the case of numeric expressions, these are constructed from variables, constants, mathematical functions, and the mathematical operations of addition, subtraction, multiplication, division, and involution.

The formation and evaluation of numeric expressions follow the normal algebraic rules, and the circumflex accent, the asterisk, the solidus, the plus sign, and the minus sign symbols are used to represent the operations of involution, multiplication, division, addition, and subtraction, respectively.

Unless parentheses dictate otherwise, exponentiation is performed first, then multiplications and divisions, and finally additions and subtractions, where operations of the same precedence are associated from left to right. So, A - B - C is interpreted as (A - B) - C, A / B / C as (A / B) / C, and A - B / C as A - (B / C), since in the first two all the mathematical operators have the same precedence, and hence evaluate from left to right, while in the last one there exists different precedence between operators, and hence the division is evaluated before the subtraction.

The following examples illustrate in a simple way the concepts seen so far:

  • a program that prints the value of the exponentiation of the numeric constant 1.4142 by 2 (also calculates the square of 1.4142), together with some text:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 PRINT "THE SQUARE OF 1.4142 IS ", 1.4142^2
30 END
  • a program that defines a numeric variable S with a value of 1.4142, and prints the value of the exponentiation of the numeric variable by 2 (also calculates the square of 1.4142), together with some text:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET S = 1.4142
30 PRINT "THE SQUARE OF ", S, " IS ", S^2
40 END
  • a program that defines a numeric variable S with a value of 1.4142, calculates the product of S by S (also calculates the square of 1.4142), assigns this value to a numeric variable S2, and prints the value of both S and S2 together with some text as string constants:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET S = 1.4142
30 LET S2 = S * S
40 PRINT "THE SQUARE OF ", S, " IS ", S2
50 END
  • a program that defines a numeric variable S with a value of 1.4142 and another one S2 with 2.0000, and prints the value of the operation of dividing S2 by S, together with some text as string constants:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET S = 1.4142
30 LET S2 = 2.0000
40 PRINT "THE SQUARE ROOT OF ", S2, " IS APPROXIMATELY ", (S2 / S)
50 END
  • a program similar to the previous one, in that it defines a numeric variable S with a value of 1.4142 and another one S2 with 2.0000, but prints the value of the operation of subtraction of S by the result of dividing S2 by S (giving then a measure of accuracy for the approximation -- this is the nucleus of a numerical method that we will see later to calculate the square root of a number), together with some text as string constants:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET S = 1.4142
30 LET S2 = 2.0000
40 PRINT S, " AND THE QUOTIENT OF ", S2, " BY ", S, " DIFFER BY ", (S - S2 / S)
50 END
  • a program a little bit different to the previous ones, in that it asks the user for a number, whose square is to be calculated:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET S = 0.0
30 PRINT "THIS PROGRAM CALCULATES THE SQUARE OF A NUMBER"
40 INPUT "PLEASE ENTER THE NUMBER WHOSE SQUARE IS TO BE CALCULATED: ", S
50 PRINT "THE SQUARE OF ", S, " IS ", S^2
60 END

Mathematical Functions

edit

Up to here we have seen how numeric and character variables are to be defined, the rules for writing lines, basic input and output, and the rules for simple arithmetic.

But what happens, if one needs to calculate the square root of a number? For this purpose, basic mathematical functions are by default provided. These are:

  • the absolute value of a number, ABS(X)
  • the arctangent of a number, ATN(X)
  • the cosine of a number expressed in radians, COS(X)
  • the exponential of a number, EXP(X)
  • the integer part of a number, INT(X)
  • the natural logarithm of a number, LOG(X)
  • the sign of a number, SGN(X)
  • the sine of a number expressed in radians, SIN(X)
  • the square root of a positive number, SQR(X)
  • a uniformly distributed pseudo-random number in the interval (0,1), RND()
  • the tangent of a number expressed in radians, TAN(X)

Let us see some examples:

  • a program that calculates the square root of 2 with the help of the SQR mathematical function provided:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET S2 = 2.0
30 LET S  = SQR(S2)
40 PRINT "THE SQUARE ROOT OF ", S2, " IS ", S
50 END
  • a program that asks the user for a number, for which its cosine is to be calculated:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET X = 0.0
30 INPUT "PLEASE ENTER THE NUMBER WHOSE COSINE IS TO BE CALCULATED: ", X
40 PRINT "THE COSINE OF ", X, " IS ", COS(X)
50 END
  • a program that asks the user for a number, for which its sine is to be calculated:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET X = 0.0
30 INPUT "PLEASE ENTER THE NUMBER WHOSE SINE IS TO BE CALCULATED: ", X
40 PRINT "THE SINE OF ", X, " IS ", SIN(X)
50 END
  • a program that asks the user for a number, for which its tangent is to be calculated:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET X = 0.0
30 INPUT "PLEASE ENTER THE NUMBER WHOSE TAN IS TO BE CALCULATED: ", X
40 PRINT "THE TAN OF ", X, " IS ", TAN(X)
50 END
  • a program that asks the user for a number, for which its exponential is to be calculated:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET X = 0.0
30 INPUT "PLEASE ENTER THE NUMBER WHOSE EXP IS TO BE CALCULATED: ", X
40 PRINT "THE EXP OF ", X, " IS ", EXP(X)
50 END
  • a program that asks the user for a number, for which its natural logarithm is to be calculated:
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 LET X = 0.0
30 INPUT "PLEASE ENTER THE NUMBER WHOSE LOG IS TO BE CALCULATED: ", X
40 PRINT "THE LOG OF ", X, " IS ", LOG(X)
50 END
  • a program to print a pseudo-random number uniformly distributed in the interval (0,1):
10 REM "SIMPLE PROGRAM FOR DEMONSTRATION PURPOSES"
20 PRINT "PSEUDO-RANDOM NUMBER UNIFORMLY DISTRIBUTED IN (0,1): ", RND()
30 END

Control Statements

edit

Sample Programs

edit

Minimal BASIC sample programs can be found in the corresponding page.


Normative BASIC/Minimal BASIC

Sample Programs

edit

Sample programs for Minimal BASIC will appear here.

Numerical Integration

edit

Introduction

edit

There exists two cases, when the computation of the value of a definite integral by numerical methods is needed. One of them is the calculation of the area below the curve defined by a set of experimental data, and another is the calculation of the definite integral of a mathematical function, for which no known integral is known. The former is often the case of response functions in the experimental labors of science and engineering, while the latter is normally the case in the practical investigations of physics, mathematics, and engineering.

Independently of it, the development of numerical methods for integration purposes, a field that belongs to the department of applied mathematics, is based on the simple idea from which it stems, i.e., if   is a real-valued (the complex-valued case can be treated analogously, by separating it into its real and imaginary parts) continuous function of   defined in an interval  , its definite integral,

 ,

can be calculated approximately as the finite sum of the product   evaluated at some given points in the interval  .

In the case of experimental data, the set of points at which the value of the function is measured is usually not regularly distributed (i.e., the points are not equispaced), so the value of the definite integral must be calculated in the form:

 ,

which can be approximated either as:

 ,

or as:

 .

In the first case, the value of the integral is underestimated (overestimated) in the case of monotonically ascending (descending) functions, since the value of   taken in each evaluation is always the lowest (highest) in every subinterval, and hence constituting an absolute lower (upper) bound to the value of the integral, while in the second case, the value of the integral is overestimated (underestimated) in the case of monotonically descending (ascending) functions, since the value of   taken in each evaluation is always the highest (lowest) in every subinterval, and hence constituting an absolute upper (lower) bound to the value of the integral.

According to the Mean-Value Theorem of Calculus, the value of a definite integral can also be calculated as:

 ,

for some value   in   for which   represents the mean value of   in  , so it is then a better approximation to calculate the definite integral of a set of experimental data as:

 ,

 ,

 .

For reasons that we shall see later, this is equal to assume a piecewise linear interpolating function between the different points, and the value of the integral so calculated is exact for linear functions (i.e., functions for which its slope changes at constant rate), although it is underestimated for functions for which its slope grows at non-constant rate (i.e., its second derivative is strictly positive in the considered interval), and it is overestimated for functions for which its slope decreases at non-constant rate (i.e., its second derivative is strictly negative in the considered interval). The value so calculated constitutes a better approximation than the lower and upper bounds presented before, and in the case that the second derivative of the function (which can be calculated from the experimental data with the help of second or central differences) changes signs between subintervals, the value is expected to be close to the actual value due to the cancellation of the errors in the approximation of the mean values.

In the case of mathematical functions, there is more information about the function, since it is possible not only to calculate the value of the function at any given point, but also to compute first, second, and higher-order derivatives with any degree of accuracy.

Let us elaborate some mathematical results, going from simple to more elaborate methods:

The main theme in the development of numerical methods, together with the study of the stability (i.e., if a method converges), is the rate of convergence of the method, which studies how many evaluations are needed and the error in the approximation, for non-iterative methods, or how many iterations are needed and how the error is minimized in each iteration, for iterative methods.

In the case of the study of the stability, and as we have seen before, the value of the definite integral of a function   defined in an interval  ,

 ,

can be calculated approximately as the finite sum of the product   evaluated at some given points in the interval  .

In the limit  , the finite sum tends to the infinite integral, and so convergence is assured.

In the case of the study of the rate of convergence, one is interested in increasing the accuracy of the approximation, while retaining the number of subintervals, with a minor increase in computational complexity.

The approach used consists normally in using a polynomial approximation for the evaluation of the function   in each subinterval, using the information provided by the value of the function at several points in the subinterval.

Let us consider the case of equally-spaced points (although this restriction can be easily lifted):

According to the definition,

 ,

with   being indicative of the subinterval,   being some arbitrary number in every subinterval  , with  , and  , and  , with  , and  .

The Mean-Value Theorem of Calculus tells us, that if

 

is the definite integral of   in  , there exists a value   in  , such that

 .

Additionally, by definition, if

 

is the definite integral of   in  , this one can also be understood as being composed of the individual contributions

 

for arbitrary values  .

Now, applying the Mean-Value Theorem to each individual contribution yields the result:

 ,

which is exact.

In the particular case that every subinterval is of equal size, i.e.,  , then the expression reduces to

 .

In this way, the calculation of the initial definite integral reduces to the calculation of the mean values

 .

In a first approximation, with only one point,

 ,

with   being the value of   in the middle of each subinterval, which leads to

 .

In a second approximation, with only two points,

 ,

with   being the value of   at the beginning and at the end of each subinterval, which leads to

 .

In a third approximation, with only three points,

 ,

with   being the value of   at the beginning, in the middle, and at the end of each subinterval, which leads to

 .

In a fourth approximation, while still making use of the evaluation of the function   at the beginning, in the middle, and at the end of each subinterval, one can use the result that if   and   are estimates for  , then its arithmetic mean   is also another estimate with at least the same accuracy, if not better.

So, adding the results for the first and second approximation, and dividing by two,

 ,

which leads to the result

 .

Adding the results for the first and third approximation, and dividing by two,

 ,

which leads to the result

 .

In practice, one can do no better with only three evaluations in an interval, but the results obtained are simple and accurate enough, even in the case of one single interval.

Let us illustrate the case by means of an example:

Let us suppose, that we wish to calculate the definite integral of the function   in the interval  , for which we know its exact value,  .

Let us also keep the problem simple and do the calculations with a single interval, i.e.,  ,  , and  .

So, we have:

First approximation:

 

This is equal to a relative error of

 .

Second approximation:

 

This is equal to a relative error of

 .

Third approximation:

 

This is equal to a relative error of

 .

Fourth approximation, first and second terms (linear expansion):

 

This is equal to a relative error of

 .

Fourth approximation, first and third terms (quadratic expansion):

 

This is equal to a relative error of

 .

In case more accuracy is needed, one can analogously introduce higher-order terms in the expansion of   around  , or half the integration step in one of the methods considered before.

Let us consider the case, when higher-order terms are considered in the expansion, i.e.,

 ,

which leads to the result

 .

Let us illustrate the case by means of an example:

Let us suppose, that we wish to calculate the definite integral of the function   in the interval  , for which we know its exact value,  .

Let us also keep the problem simple and do the calculations with two intervals, i.e.,  ,  ,  ,   and  .

Applying second order expansion

 ,

which yields

 ,

which is equal to a relative error of

 .

Applying fourth order expansion

 ,

which yields

 .

We know from the Calculus of Differences, that any function can be expressed as the polynomial expansion

 

in the case of forward differences, or

 

in the case of backward differences, or

 

in the case of central differences.

In a first approximation,

 

 

in the case of forward differences,

 

 

in the case of backward differences,

 

 

in the case of central differences.

So, in the case of evaluating the integral with one single point, the value of it is always underestimated (overestimated) with forward (backward) differences if the value of the slope of the function at the evaluation point is positive, and underestimated (overestimated) with forward (backward) differences if the value of the slope of the function at the evaluation point is negative, being the error in the estimation directly proportional to the slope of the function at the evaluation point, and to one half of the square of the integration step. In the case of evaluating the integral with central differences, the value is exact for linear functions.

In a second approximation,

 

 

 

 

in the case of forward differences,

 

 

 

 

in the case of backward differences,

 

 

 

 

in the case of central differences.

So, in the case of evaluating the integral with a linear function, there is no difference between forward and backward differences, and the value of the integral is equal to the product of the mean of the values of the function at the beginning and at the end of the interval times the integration step, being the value so calculated underestimated (overestimated) for monotonically increasing (decreasing) functions with a positive (negative) second derivative, the error in the approximation being directly proportional to the second derivative of the function and to the cube of the integration step (i.e., as one increases the number of subintervals, one reduces the deviation proportional to the cube of the number of subintervals). In the case of central differences, the value of the integral is equal to the product of the value of the function in the middle of the interval times the integration step, as in the previous case, the error in the approximation being reduced by a factor of four with relation to the case of forward and backward differences.

In a third approximation,

 

 

 

 

 

 

 

 

in the case of forward differences,

 

 

 

 

 

 

 

 

in the case of backward differences,

 

 

 

 

 

 

 

 

in the case of central differences.

In a fourth approximation,

 

 

 

 

 

 

 

 

in the case of forward differences,

 

 

 

 

 

 

 

 

in the case of backward differences,

 

 

 

 

 

 

 

 

in the case of central differences.

The divided differences are:

 

 

 

 

Lagrange interpolation

One point:

 

Two points:

 

Three points:

 

Four points:

 

Five points:

 

Six points:

 

Seven points:

 

One point:

 

 

 

 

Two points:

 

 

 

 

 

 

 

 


Three points:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Four points:

 

 

 

 

 

 


 

 


 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 


 

 


 


S-Sum  

 

 

Let us consider the integrals

 

 

 



An analytical method of calculation of the relative weights of the evaluations of the function   at the points  , consists in evaluating the integral of the function   as the integral of a polynomial approximation.

If one chooses the value of   as  , i.e., at the beginning of every subinterval, then the sum of products is equal to:

 ,

If one chooses the value of   as  , i.e., at the beginning of every subinterval, then the sum of products is equal to:

 ,

Let us consider the case of equally-spaced points (although this restriction can be easily lifted), according to the definition,

In the case of a semi-continuous function, i.e., a function which is continuous except for a finite numerable set of points in an interval  , the calculation of the definite integral can be defined as the sum of the definite integrals between the points of discontinuity, i.e.,

 .


Beginning BASIC/Your First Program

Introduction

edit

Many texts written about programming languages show you a sample program at the beginning of the lesson to help get your feet wet. That is, to become familiar with the syntax and layout of that language. This book is no exception. This sample program will display the text "Hello, world!" to your screen.

Program Examples

edit

Example One (FreeBASIC)

10 CLS
20 INPUT " Enter Your Name ", X
30 PRINT X = " YOUR NAME"
40 END

.

Explanation

edit
  1. CLS stands for 'Clear Screen' and erases everything in the Command Prompt.
  2. PRINT displays everything in between the quotations.
  3. INPUT gives input and tell what to do.
  4. END marks the end of the program (explained later in functions.)
edit

Wikipedia's article on Hello World

  Index Next: Beginning BASIC/PRINT, CLS, and END


Beginning BASIC/PRINT, CLS, and END

BASIC Programming > Beginning BASIC > Your First Program


Introduction

edit

In the previous code example, we wrote your first BASIC program. In it, you saw examples of PRINT, CLS, and END commands. Their roles in the program may or may not have been apparent at the time, but, as they're so vital to the BASIC language, they will be discussed here.


10 CLS
20 PRINT "Hello, world!"
30 PRINT "I'm making the sample program clear and understandable."
40 PRINT "This text is being printed via the PRINT command."
50 PRINT "On the next line, I'll use CLS, which will clear everything I just printed, so you won't even see the preceding text."
55 PRINT "Also, you can't give CLS a line to PRINT; it won't actually do anything"
60 CLS "These words actually do nothing; they do not PRINT or anything."
70 PRINT "Finally, on line 80, I'll use END, which will keep me from reaching line 90."
80 END "Like CLS, putting a string here does nothing; it does not PRINT or anything."
90 PRINT "this is not really my answer."

Output

edit
(CLS)
Hello, world!"
I'm making the sample program clear and understandable."
This text is being printed via the PRINT command."
On the next line, I'll use CLS, which will clear everything I just printed, so you won't even see the preceding text."
Also, you can't give CLS a line to PRINT; it won't actually do anything"
(CLS)
Finally, on line 80, I'll use END, which will keep me from reaching line 90."
(END)

-Program end-

Discussion

edit

From that example, it's fairly easy to deduce what each command does.

CLS
An abbreviation that stands for the words CLear Screen. In the above program, when you used CLS on line 60, all of the words that were printed to the screen were wiped away.
PRINT
Writes to the screen. There are commands for printing to other things, like a printer, but that's to be discussed later. Each new PRINT command will start printing on a new line. To insert a blank line, don't specify a string to print. The syntax for "PRINT" is: PRINT "[whatever you want to be printed here]"
END
It stops the program at that line; that is, anything that's added after that won't show. That's why the PRINT command on line 90 didn't print anything. The END command can be included in control structures to end the program if a condition is met. This will be discussed with control structures.


What is happening?

  1. Line 10 the display is cleared.
  2. Lines 20 through 50 print text to the screen.
  3. Line 60 clears the display.
  4. Line 70 shows the message you should see after you run this program.
  5. Line 80 ends the program.
  6. Line 90 shows that an END statement stops the program. No instruction following an END statement is executed.

Given the state of computer speed today you should not see the paragraph displayed by lines 20 through 50, it should be cleared by the CLS statement on Line 60 before you have a chance to see it. If you slow the program down you can see the program write the message to the screen. Line 70 is then written to the screen/display then Line 80 stops everything. Line 90 never, ever runs.


Previous: Beginning BASIC/Your First Program Index Next: Beginning BASIC/Variables and Data Types


Beginning BASIC/Variables and Data Types

Variables allow you to store and change information. Below is an example how to use variables.

Example Code for Variables

edit

Example 1 (qBasic)

CLS
ASTRING$ = "Hello World"
ANUMBER% = 10
PRINT ASTRING$
PRINT ANUMBER%

Example 1.2 (freeBasic)

Cls
Dim aString As String
Dim anInteger As Integer
aString = "John Doe"
anInteger = 42
Print aString
Print anInteger
Sleep
End

Output

edit

Example 1

Hello World
10

In Basic, a string variable ends in a $, and whole number variables, known as integers, end with a %.

Example 2

John Doe
42

If you use Dim varName As DataType to declare variables, you do not need to use a suffix.

Arrays

edit

An array is a collection of values.

Cls
Dim aNames(3) as String
aNames(1)="John Doe"
aNames(2)="Jane Doe"
PRINT aNames(1)
PRINT aNames(2)


Beginning BASIC/User Input

Introduction

edit

Read the Variables and Data Types article before reading this one.

User Input is one of the most important aspects of programming concepts. Every program should have some sort of user interaction, from getting a character's name for a game to asking for a password to log into a database. This article will teach the basics of user input in the BASIC Programming Language. Please note that the following code may vary from compiler to compiler. (FreeBASIC Users: Do not use line numbers).

Code

edit
  1. you can copy it from here, hashtags do not do anything, it's a reminder.

Example 1 (qBasic)

CLS
10 PRINT "what is your name?"
20 INPUT "...(Enter Your Name)...", a$
30 PRINT
40 PRINT "hello, "; a$; ", I am your computer, nice to meet you."
60 END

Example 2 (freeBasic)

10 Dim userInput As String
20 Input "What is your name?", userInput
30 Print
40 Print "Hello, " ; userInput ; "! I am your computer, it's nice to meet you."
50 Sleep
60 End

Explanation

edit

Output

What is your name?
...(Enter Your Name)...

Hello, yourName, I am your computer, nice to meet you.

10: Dim userInput declares the variable userInput. As String tells the compiler that userInput is a string (A collection of pure text, can include numbers and symbols, but is considered text).
20: Input "What is your name?" prompts the user for their name. userInput OR a$ tells the compiler to store the answer in the variable in userInput or a$.
30: Makes a blank line.
40: A normal Print statement, ; tells the compiler not to skip to the next line.
50: Sleep makes the program wait for the user to press a key.
60: The ending to all BASIC programs, signifies a termination of the program.


Previous: [[../../Beginning BASIC/Variables and Data Types|Variables and Data Types]] Main: BASIC Programming Next: [[../../Beginning BASIC/Documentation|Documentation]]


Beginning BASIC/Documentation

Introduction

edit

In Basic, code is documented in one of two ways:

  • a remark, indicated by the REM statement
  • a full-line comment introduced by an apostrophe: (')

Either of these two methods will result in treating the rest of the line as a comment. The interpreter will discard the rest of the line.

As with most forms of code documentation, it needs to be used as programs grow larger and to help identify the purpose of a given section of code. It is unnecessary to document every individual line, but should give enough information such as the purpose of a given function or why a certain statement may be needed.

Code

edit
first example (qBasic)
CLS
10 PRINT "Hello World!"
20 REM This code will display Hello World! to the display.
30 END
second example (freeBasic)
print "Hello World!"
'This code will display Hello World! on the screen
sleep
end

Explanation

edit

This will allow you to create a Remark statement that will not be visible to the user, but will be visible when the code is reviewed.


Previous: [[../../Beginning BASIC/Variables and Data Types|Variables and Data Types]] Main: BASIC Programming Next: [[../../Beginning BASIC/Documentation|Documentation]]


Beginning BASIC/Control Structures/IF...THEN...ELSEIF...ELSE

The IF...THEN...ELSEIF...ELSE control statement allows identifying if a certain condition is true, and executes a block of code if it is the case.

10 CLS
20 IF number<0 THEN PRINT "Number is negative" REM Single line if
30 ELSEIF number>0 THEN
40   PRINT "Number is positive" REM Two line if/elseif
50 ELSE
60   PRINT "Number is zero"
70 END IF

In some implementations of BASIC (but permitted by most versions), the IF statement may need to be contained in one line. However, ELSEIF may not be available in this case, and there is no need for an explicit END IF:

10 CLS
20 IF number<0 THEN PRINT "Number is negative" ELSE PRINT "Number is non-negative"

This carries over into some implementations of BASIC where if the "IF...THEN" statement is followed by code on the same line then it is fully contained. That is, the compiler assumes the lines ends with "ENDIF", even if it not stated. This is important when dealing with nested "IF...THEN" clauses:

10 CLS
20 IF X<2 THEN
30   IF 2<3 THEN PRINT "This is printed if X is 1"
40 ELSE
50   IF 3<4 THEN PRINT "This is printed if X is 3"
60 END IF

The ELSE clause, while following the "IF 2<3" statement, is associated with the "IF X<2" statement, because the "IF 2<3" statement has a PRINT statement on the same line.

Let me give some more examples of "if-then-else" programs:

Q1)Input the age of a person and check whether he/she is voter or not?

Ans1) 10 CLS 20 INPUT AGE 30 IF AGE>=18 THEN 40 PRINT "VOTER" 50 ELSE 60 PRINT "NON VOTER" 70 END IF 80 END

Q2)Input the age of a person to check if he/she is a senior citizen or not a senior citizen?

Ans2) 10 CLS 20 INPUT AGE 30 IF AGE>=60 THEN 40 PRINT "SENIOR CITIZEN" 50 ELSE 60 PRINT "NOT A SENIOR CITIZEN" 70 END IF 80 END


Beginning BASIC/Control Structures/WHILE...WEND

 INPUT "What is your name"; UserName$
 PRINT "Hello "; UserName$
 DO 
   INPUT "How many stars do you want"; NumStars
   Stars$ = ""
   Stars$ = REPEAT$("*", NumStars) '<-ANSI BASIC
   'Stars$ = STRING$(NumStars, "*") '<-MS BASIC
   PRINT Stars$
   DO
     INPUT "Do you want more stars"; Answer$
   LOOP UNTIL Answer$ <> ""
 LOOP WHILE UCASE$(LEFT$(Answer$, 1)) = "Y"
 PRINT "Goodbye ";
 FOR A = 1 TO 200
   PRINT UserName$; " ";
 NEXT A
 PRINT


Beginning BASIC/Control Structures/FOR...NEXT

The FOR...NEXT loop is a form of flow control that places focus on a single counter.

The basic syntax is simple - a variable is given a starting value and ending value, and it increments on each pass of the loop:

FOR i = 1 TO 10
NEXT

A more advanced loop includes the STEP parameter, which specified the value at which a variable is incremented. It can be negative to have the loop decrease the variable instead of increasing it, and may even be fractional. An example of a reverse counting loop is as follows:

FOR i = 10 TO 1 STEP -1
NEXT

The FOR loop terminates when the variable passes the final value in the loop. This is checked by determining if it is greater than the second parameter (or less than if STEP is negative.)

If desired, you can place variables within the start and end parameters instead of constant numbers.


Beginning BASIC/Control Structures/DO...LOOP

In the last chapter we learned about inputing data to the program. Well now you'll be learning how to repeat a function over and over again. Remember anything to the right of an apostrophe (') are comments in one version of BASIC, and should be removed, or replaced with a different kind of REMARK, if they cause problems.

CLS 'Clears screen for user

DO 'Starts the Looping process, anything between this and the LOOP command will be repeated.
  PRINT "You will get this message over and over." 'Displays the message "You will get this message over and over."
LOOP ' Shows where objects should stop being looped.

This loop will continue forever, unless interrupted by the operating system. If you wanted to have a condition where the loop ends, you can put a WHILE or UNTIL keyword after LOOP.


Beginning BASIC/Control Structures/GOTO

The GOTO statement in BASIC is used to jump to a specific location or label within the source code; it may take either a line number (which appears at the beginning of a line) or a label (which is a word that ends in a colon).

This statement was originally essential for programming in Basic; the older interpreters only allowed IF statements to run on one line and did not have more advanced handling of FOR or WHILE loops. Under modern versions of Basic, you will generally see GOTO used only to return to the top of a main loop. In all other cases, usage of GOTO has been deprecated in favor of other statements.

GOSUB

edit

The Gosub statement is a variation of the Goto statement. When used, it jumps to a specific location within the program, and allows the next RETURN statement to head back to the point just after the GOSUB call.

This statement must be paired with a matching return statement. Under modern versions of Basic, GOSUB uses a stack of locations that may be filled up, resulting in a stack overflow.


Random Number Generation

One useful thing for games is random numbers. This is a sequence of numbers that appears randomly distributed, so they can be used to simulate things like shuffling a deck of cards or producing different behaviours every time a program runs.

Random numbers in BASIC are generated by the RND function. This returns a number between 0 and 1. For example:

PRINT "Wikibooks' coolness quotient: ", RND, "%"

You will get "Wikibooks' coolness quotient: .7055475%".

That result looks random. Run it again and you get the same value! That makes a game boring. This is the purpose of seeding, which is normally accomplished with the RANDOMIZE statement. In modern dialects, this can be tied to the clock using the TIMER keyword:

RANDOMIZE TIMER
PRINT "Wikibooks' coolness quotient: ", RND, "%"

which will print "Wikibooks' coolness quotient: .8532526%" and another time will print "Wikibooks' coolness quotient: .3582422%". Better, right?

But decimal numbers are not always useful. If you want a whole number, you must get a random number and then convert it to a whole number. Normally you want that number to be between two limits, say 0 and 100. One solution is to take the number, multiply by the maximum desired value, add half to round it, and then take the whole number part. Some slight variation on the following code is very common:

PER = INT(RND() * 99 + 0.5)

Modern dialects like QBASIC offer more control. We can state the variable is an integer, and BASIC will force it to that format and slightly simplify the code:

RANDOMIZE TIMER
DIM PER AS INTEGER
PER = RND * 100 + 0.5
PRINT "Wikibooks' coolness quotient: ", PER, "%"

which will print "Wikibooks' coolness quotient: 85%".


Subroutines and Functions

Functions and Subroutines are lines of code that you use more than once. The purpose of functions and subroutines is to save time and space by just calling a function/subroutine. There is hardly a difference between the two, except that a function returns a value, where a subroutine just repeats lines of code (A function is not always used more than once).

An example of a function, say you are making a program that calculates sales tax. The function would ask for a subtotal, take that number and multiply it by 1.07 (If sales tax is 7%, the 1 is because you are adding onto the subtotal to make a total, not finding the sales tax itself). The function would take the new total and give it back to the program.

A subroutine would be code that is reused, like a shop in a game. Every time the user goes to the shop, the program will go back to the Shops Subroutine, and if the user bought an item, it would call a "Buy Item" function.

Parameters

edit

Parameters are used in functions and subroutines. They pass data to be used with the function/parameter. For use with our two examples:

Function Parameters) The Subtotal passed to the function is a parameter.
Subroutine Parameters) The player's amount of gold could be sent to the subroutine so the shop
knows how much money the player can spend.

There are two different ways to send parameters: by the value or by reference. By Value means that the function can not actually change the data outside of the function, but can use its data to manipulate other data that is returned. By Value is like making a carbon copy of a paper and then editing the carbon copy. By Reference sends the actual argument (parameter) to the function/subroutine, which is like editing the original copy of the paper. By Value is written as ByVal and By Reference is written as ByRef.

Functions

edit

Ignore the line numbers; they are used for explaining the code.
Example 1 (FreeBASIC)

1. Declare Function salesTax(ByVal subTotal As Double) As Double
2. Dim SubTotal2 As Double
3. Dim Total2 As Double
4. SubTotal2 = 10.00
5. Total2 = salesTax(SubTotal2)
6. Print "Subtotal:" ; SubTotal2
7. Print "Total:" ; Total2
8. Sleep
9. End
10.
11. Function salesTax(ByVal subTotal As Double) As Double
12.   Dim Total As Double
13.   Total = subTotal*1.07
14.   return Total
15. End Function



1. This line is the function's prototype. Functions must be declared as a prototype before they are used, and must be defined after the end (of the program) statement. Function means that the following is related to functions. salesTax is the function identifier or its name, and in parentheses are the parameters (If you have more than one parameter, separate them with a comma). After the parentheses tells what Data Type the function returns. Double is a Data Type that signifies a number with decimals (00.00).
2. Create the SubTotal2 variable (Parameters can not be the same as existing identifiers).
3. Create the Total2 variable.
4. Define SubTotal2 with the value 10.00 (Change this to get new outputs)
5. Define Total2 by passing SubTotal2 as an argument(parameter) to the function salesTax (The value of Total2 will be what the function returns).
6. Display the subtotal.
7. Display the total.
8. Wait for the user to press enter (So you can read the output with out it flashing away in a second).
9. End the program (In a sense. You can't interact with the user past the End point)
10. Blank Line, easier to read the code.
11. This is where you define the function, earlier you declared the function.
12. Create the variable Total (This variable can only be used in the function, because it was defined in the function. This is called the variable scope).
13. You do not need to declare subTotal, because it was defined as a parameter, this math finds the total with sales tax and assigns it to the variable Total.
14. This is what line 5 receives, the function shoots out the variable Total.
15. Ends the function definition.

GOSUB ... RETURN Statement

Purpose:

To branch to, and return from, a subroutine. Syntax:

GOSUB line number
.
.
.
RETURN [line number]

Comments:

line number is the first line number of the subroutine.

A subroutine may be called any number of times in a program, and a subroutine may be called from within another subroutine. Such nesting of subroutines is limited only by available memory.

A RETURN statement in a subroutine causes GW-BASIC to return to the statement following the most recent GOSUB statement. A subroutine can contain more than one RETURN statement, should logic dictate a RETURN at different points in the subroutine.

Subroutines can appear anywhere in the program, but must be readily distinguishable from the main program.

To prevent inadvertent entry, precede the subroutine by a STOP, END, or GOTO statement to direct program control around the subroutine. Examples:

10 GOSUB 40
20 PRINT "BACK FROM SUBROUTINE"
30 END
40 PRINT "SUBROUTINE";
50 PRINT " IN";
60 PRINT " PROGRESS"
70 RETURN
RUN
SUBROUTINE IN PROGRESS
BACK FROM SUBROUTINE

The END statement in line 30 prevents re-execution of the subroutine.

Conclusion

edit

Subroutines do not return any values, while functions return values. Subroutines are also allowed to change values of the parameters while functions are supposed to maintain.


External Libraries

// Code your testbench here // or browse Examples

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="index.js"></script>
  </body>
</html>