Table of Contents:
|
Your first program Directly from Rockerfer Basic site's Main Page, you will be able to write your first program. Inside the window, write the following line:
Run this program by clicking on "Run!". The line "Hello World" will be shown when the web page reloads. This means the program was run correctly. The print instruction allow your programs to show information in the computer screen. If you use several print instructions, one following the other, you will note the printed sentences will be shown one below the other. For example:
Will show:
However, if the sentence is ended with a comma (,), the next print sentence will print in the same line as the previous one.
You can separate several to-be-printed elements using commas:
Synonims In Rockerfer Basic there are a few synonims, so you can write one instruction more than one way. Thus, print can be written as say, write, and the symbol '?'. In the next example, all the sentence do exactly the same action:
Which one to use? The one you feel like using. That's the idea! That way you will be able to design for programs comfortably, without worrying about cumbersome syntaxis. Variables and Datas Rockerfer Basic has three types of data: Integer, floating and string. The integer type represents any real, integer (no decimals) number, positive or negative. The floating type accepts any real number (with decimals. Scientific notation may be used). The string type represents any series of alphanumeric characters (letters, numbers and symbols).
Data in Rockerfer Basic can be handled literally, or stored in variables. Literal handling refers to direct use of data inside a sentence. Next you will find examples of literal handling inside the print sentence:
Variables are individual data storage areas identified by an associated name. Variables can store data of any allowed type in Rockerfer Basic, that is, there are variables that store integer data (called integer variables), there are variables that store floating data (floating variables) and there are variables that store string data (string variables). Integer or floating variables are also referred as numeric variables. String variables are also referred as alphanumeric variables. Variables are identified with a name. Examples of variable names follow:
Variables can only store data of the type it was assigned. For example, a numeric variable can not store alphanumeric strings (such as letters or words). There are two ways to declare a variable. The first one is by using the declare instruction:
If the type is omitted, integer will be assumed. Arrays There are special variables that can store more than one value of the same type at the same time. These are the matrixes or arrays. Arrays are collections of data stored in variables of the same type and under the same name. How can you identify a piece of data in particular, if all variables in the array have the same name? Each variable has a numeric attribute called index. The index is unique for every piece of data; thus, we can refer to a variable that is member of the array by its name and index. An array of 5 integers is shown next:
Let's say the array uses the identification name "Values". That way you can refer to any value by writing the variable name along with its index in parenthesis:
In the previous example, it can be noted that array indexes are sequential, and are counted starting from 1. For example, an array of 25 strings has its values arranged from 1 to 25. Arrays can be used in any context where a regular variable can be used. Here are a few examples:
As you can see, in order to declare arrays you just have to add array and the index between parenthesis in the declaration sentence. Assigning data to variables What is the second way to declare variables? First, let's review the way data is assigned to variables. This is done with the let sentence. In the next example, the string "Hello" will be assigned to the string variable Greetings.
Variables can be assigned values as many times as required. Values can only be the same type of the variable. If you try to assign a string to a floating variable, Rockerfer Basic will report an error. The exception is when you assign an integer to a floating variable. In that case, it will work, although the integer value will be converted implicitly to the floating type. The other way around will work, too, but if the floating value has decimals, these will be silently deleted.
You can omit the Let instruction when assigning:
Back to the second method of declaring variables: If you assign a value to a variable that was not previously declared, it will be automatically created and will be the type of the assigned value:
Arrays must always be declared before assigning values to them. Programming Structures Rockerfer Basic provides a set of sentences to create programming structures, where the program flow changes according to a series of conditions. These structures are studied in every introductory programming course. The most common will be discussed here. To review them all, see the Complete Reference. for / to /end for This structure allows to execute a section of the program as many times as specified. For example, next sentence:
will print "Hello" once. If you require to print "Hello" 100 times, there are various alternatives. The first one is to execute the program 100 times. The second one is to write a program with 100 print "Hello" sentences. Both alternatives are extremely inefficient. The third alternative is to use a for / to / end for structure:
If you execute the previous program, "Hello" will be printed 100 times. The for / to / end for has various options. See the Complete Reference for more information. if / then / end if This structure allows the program to decide whether or not to execute a program section (or block), depending of a certain condition. For example:
When Rockerfer Basic reaches the second line of this program, it will check the condition of the structure (in this case, it will check if the value of the variable Age is greater than 10). If the condition is true, it will execute the section starting the third line (in our example, it will be executed because the condition is indeed true, that is, Age, which is 17, is greater than 10). If Age would have had the value 9 instead of 17, Rockerfer Basic wouldn't have executed the third line. It would have skipped it and continue the execution starting the line after the end if. repeat / until This structure executes a program block repeatedly until a certain condition is proven true. For example:
The previous program will ask a password to the user. Let's assume the user provides a password different to "secret". When Rockerfer Basic reaches the fourth line, it will verify if the condition is true (that is, is Password equals "secret"). Is it is not true, then it will execute the sentences starting from repeat again. When the user provides the word "secret" as a password, and Rockerfer Basic reaches the until sentence, it will continue with the remaining instructions, since the condition is now true (Password = "secret"). The structures here superficially discussed have more options that allow to write programs more flexibly. The Complete Reference will show you those options as well as the other programming structures. Built-in Functions Rockerfer Basic has a set of functions to perform common programming tasks. Each function has its own name (related to its task), and it works on data provided by the user (these data are known as parameters). For example, to print the first n characteres of a string, the right() function is used:
The previous program will print "Ale". right() has its counterpart, left(). Example:
The previous program will print "gs". Functions can be used in any expression that requires a value:
The previous Program will print the string "Whatyou?". Functions not only return alphanumeric values. As an example, the len function will return the number of characters contained in a string:len("hello") will return 5. cos() will return the cosine of a number. abs() will return the absolute value of a number. For a complete list of functions available in Rockerfer Basic, read the section List of Rockerfer Basic's Built-in Functions. |
El lenguaje Rockerfer Basic está especialmente diseñado para el aprendizaje de conceptos vistos en las etapas iniciales de los cursos de programación. Está basado en el lenguaje de pseudocódigo, lo cual significa que su juego de instrucciones representa una generalización de los juegos de instrucciones de otros lenguajes. Structure of a Rocker Basic Program Structure of a Rocker Basic Program
Las declaraciones de variables y datos pueden aparecer en
cualquier parte del programa, pero es común colocarlos
en el principio del mismo. Las declaraciones de
variables y datos pueden hacerse en cualquier lugar del
programa, aunque es recomendable que todas estén en el
principio. De esta manera están más accesibles en
momentos de depuración y modificación.
Data Types
Los datos en Rockerfer Basic pueden representarse mediante cualquiera de estos tres tipos de datos, y pueden almacenarse en variables (véase a continuación) o ser utilizados directamente en instrucciones, tales como "imprimir". Las variables son espacios de almacenamiento de datos con nombre. Se les puede hacer referencia usando su nombre. Los nombres de variables pueden ser de cualquier longitud hasta 64 caracteres, y pueden utilizarse letras, números, y el símbolo del subrayado "_", aunque no está permitido que el nombre comience con un número o el símbolo del subrayado. Rockerfer Basic no distingue las mayúsculas de las minúsculas en los nombres de variables por lo que, a manera de ejemplo, los tres nombres de variables "EDAD", "edad" y "Edad" representan todos a la misma variable. Rockerfer Basic tampoco
permite el uso de nombres de variables que coincidan con
nombres de instrucciones o funciones. Por ejemplo, el
nombre de variable "imprimir" no está
permitido, ya que imprimir es una instrucción. Ejemplos de nombres válidos:
Ejemplos de nombres no válidos:
Rockerfer Basic posee un tipo
de variable por cada tipo de dato, más las variables
matrices (véase más adelante). Es decir, que están
disponibles las variables de tipo entero, las de tipo
flotante y las de tipo cadena.
Donde <nombre>
es un nombre de variable, y <valor> es el valor a
asignársele.
Esto asignará 1 a la
variable X.
Es de preferencia del usuario escoger qué sentencias utilizar. Matrixes
(or arrays)
éstas pueden almacenarse en una matriz. Llamemos "numeros" a esa matriz, y asignémosle las cadenas.
Podemos referirnos a cualquiera de esos elementos utilizando el número de índice, que es el número ubicado entre paréntesis. Por ejemplo, las siguientes dos sentencias:
Hará que Rockerfer Basic
imprima "dos" en la ventana de salida. Declarar variable <tipo> [de arreglos] <nombre_de_variable>(<indice>) Como ejemplo, para declarar una matriz B de 10 elementos enteros, utilizamos:
Otra alternativa:
Si no se coloca el tipo, Rockerfer Basic asume el tipo entero.
La sentencia anterior declara una matríz B de 10 elementos que van desde B(1) hasta B(10). Instructions
in Rockerfer Basic
Puede escribirse como:
O incluso:
Otro ejemplo, es la
sentencia "imprimir", la cual puede escribirse
como "imprime", "escribe",
"escribir", o incluso "decir" o
"dí". List of Rockerfer Basic's Instructions and Sentences (in alphabethical order) Las palabras encerradas entre paréntesis representan alternativas a la sintaxis original. cases/case/end cases
Rockerfer Basic evaluará cada
una de las expresiones hasta que una de ellas concuerde
con el valor de <variable>. Al encontrar un valor
coincidente, Rockerfer Basic ejecutará las sentencias
correspondientes a ese caso. Si hay dos o más valores
iguales, Rockerfer Basic ejecutará sólo las sentencias del
primer valor. Si no consigue ningún valor, el
intérprete ejecutará <sentenciasO>, de Comment symbol ('#')
Especifica que el
resto de la línea es un comentario de programa y que el
intérprete deberá ignorar. De esa manera, el
intérprete continuará con la siguiente línea de
programa. 'comentario' es útil para colocar
observaciones, comentarios, explicaciones y anotaciones
dentro del código del programa. declare variable (create)
Esta sentencia es
utilizada para crear variables del tipo especificado. Si
el tipo no se especifica, se asume el tipo entero. end (finish) Utilizado para denotar
el final del programa. Todo lo que venga después no
será tomado en cuenta. Si se omite, el intérprete
asumirá el final del programa como el final del archivo. print (say, write, '?')
Se utiliza para mandar
información a la salida en pantalla del usuario. input (read,enter)
Se utiliza para
asignar valores entrados por teclado a las variables
especificadas. Rockerfer Basic esperará a que el usuario
presione la tecla ENTER para asignar un valor a una
variable, y después esperará por la siguiente variable. while / do / end while
Rockerfer Basic evaluará
<expresión> y a continuación ejecutará
<sentencias1>. Esto lo hará repetidas veces hasta
que <expresión> se evalúe como verdadera. Si
<expresión> es falsa en la primera evaluación,
<sentencias1> nunca se ejecutará. for / to / end for
Rockerfer Basic inicializará
<variable> con <expresión1>, e incrementará
su valor hasta que sea igual o supere a
<expresión2>. Por cada incremento, ejecutará las
sentencias encerradas entre 'hacer' y
'fin'.<variable> será incrementada en una unidad,
a menos de que se especifique el incremento con 'pasos'.
Si <expresión1> sobrepasa en la primera pasada a
<expresión2>, el código no se ejecuta.
<variable> puede utilizarse dentro del ciclo.
Adviértase que <variable> no puede ser parte de un
arreglo. repeat / until
El intérprete
ejecutará <sentencias1> y a continuación
evaluará <expresión1>. De resultar falsa, el
intérprete vuelve al principio de <sentencias1> y
repite el mismo proceso. <sentencias1> se
ejecutará al menos una vez. let ('=')
'sea/igual a' es un operador
de asignación de variables. Puede ser utilizado
para crear e inicializar variables (pero no se pueden
crear arreglos). Si se especifica un índice, entonces se
crea un arreglo (o matriz) de tantas variables como lo
especifique dicho índice. if / then / end if
El intérprete
evaluará <expresion>, y de resultar verdadera,
ejecutará <sentencias1>. Si resulta falsa
entonces, de existir, ejecutará <sentencias2>. Si
no se especifica <sentencias2>, sencillamente
pasará a ejecutar la siguiente sentencia. end (finish)
Este comando le indica a Rockerfer Basic que termine con la ejecución del programa. Rockerfer Basic dejará de ejecutar instrucciones una vez que encuentre una instrucción terminar. List of Rockerfer Basic's Built-in Functions (in alphabethical order) Estas funciones pueden ser utilizadas en cualquier expresión válida de Rockerfer Basic. abs(n) n puede ser un valor numérico cualquiera (flotante o entero). Devuelve el valor absoluto de n. Ejemplo: abs(-3) devuelve 3. rnd() Devuelve un número flotante aleatorio mayor o igual que 0 y menor que 1. Ejemplo: aleatorio() devuelve 0.23452347 str(n) n puede ser un valor numérico cualquiera (flotante o entero). Devuelve n como una cadena alfanumérica. Ejemplo: cadena(34) devuelve "34" (como cadena). cos(n) n puede ser un valor numérico cualquiera (flotante o entero), representando un valor en radianes. Devuelve el coseno de n, donde n es un ángulo en radianes.. Ejemplo: coseno(0) devuelve 1. right(s,n) s es una cadena. n es un entero. Devolverá los n caracteres por la derecha de s. Ejemplo: derecha("Hola",2) devuelve "la". int(n) n puede ser un valor numérico cualquiera (flotante o entero). Devuelve la parte entera de n. Ejemplo: entero(67.89) devuelve 67. exp(n) n puede ser un valor numérico cualquiera (flotante o entero). Devuelve el valor exponencial de n. Ejemplo: exp(1) devuelve 2.71828182845905 (e). left(s,n) s es una cadena. n es un entero. Devolverá los n caracteres por la izquierda de s. Ejemplo: izquierda("Hola",2) devuelve "Ho". log10(n) n puede ser un valor numérico cualquiera (flotante o entero). Devolverá el logaritmo en base 10 de n. Ejemplo: log10(10) devuelve 1. logn(n) n puede ser un valor numérico cualquiera (flotante o entero). Devolverá el logaritmo natural (o neperiano) de n. Ejemplo: logn(1) devuelve 0. len(s) s es una cadena. Devolverá el número de caracteres contenidos en s (recuerde que los espacios en blanco cuentan como caracteres). Ejemplo: longitud("Hola") devuelve 4. sqr(n) n puede ser un valor numérico cualquiera (flotante o entero). Devuelve la raíz cuadrada de n. Ejemplo: raizc(9) devuelve 3. sin(n) n puede ser un valor numérico cualquiera (flotante o entero). Devuelve el seno de n, donde n es un ángulo en radianes. Ejemplo: seno(0) devuelve 0. sgn(n) n puede ser un valor numérico cualquiera (flotante o entero). Devolverá 1 si n es mayor que 0, 0 si n es 0, y -1 si n es menor que 0. Ejemplo: signo(-15) devuelve -1. mid(s,n,m) s es una cadena. n y m son valores enteros. Devolverá los m caracteres consecutivos de s, partiendo desde n. Si m es omitido, devolverá todos los caracteres de s partiendo desde n. Ejemplo:
subcadena("Hola",2,2) devuelve "ol". tan(n) n puede ser un valor numérico cualquiera (flotante o entero). Devuelve la tangente de n, donde n es un ángulo en radianes. Ejemplo: tangente(0) devuelve 0. val(s) s es una cadena. Devuelve el equivalente numérico de s. Ejemplo: valor("34.5") devuelve 34.5.
|
© 2005 Rafael Pacheco. All Rights reserved.