1. Microsoft® Small Basic
Bifurcaciones y Subrutinas
Tiempo estimado para completar esta lección: 1 hora
2. Código Bifurcaciones y Subrutinas
En esta lección, usted aprenderá cómo:
Código de bifurcación mediante el
uso de sentencias Goto.
Crear subrutinas mediante
declaraciones Sub y EndSub.
3. Bifurcación
Como sabes, la computadora ejecuta un
programa mediante la lectura y
procesamiento de las declaraciones línea por
línea, uno a la vez.
A veces, quizás desees que la
computadora rompa el flujo y salte
a otra línea de código mientras se
está ejecutando el programa.
Puedes indicar a la computadora
que procese una secuencia de
líneas de código utilizando la
instrucción Goto.
4. Bifurcaciones en programas de Small Basic
Examinemos la instrucción Goto y sus
diversas partes al escribir un programa. En este programa, la
declaración que se llama
lineQ: es una etiqueta.
Puedes agregar tantas
etiquetas como quieras y
nombrarlas como quieras,
siempre y cuando no uses el
mismo nombre más de una
vez.
La declaración Goto da
instrucciones a la
computadora para ejecutar
las declaraciones después de
la etiqueta lineQ: solamente
si la condición en la
declaración If es cierta.
5. Bifurcaciones en programas de Small Basic
También puede utilizar la instrucción Goto para hacer correr
un programa para siempre.
Vamos a ver cómo
funciona la sentencia Goto
en un programa de
familia.
Este programa continuará
funcionando hasta que
alguien hace clic en el
botón Cerrar (X) en la
esquina superior derecha
de la ventana de texto.
6. Subrutinas en programas de Small Basic
Cuando escribimos programas, a menudo queremos que la computadora
ejecute ciertas declaraciones más de una vez. Puedes evitar escribir las mismas
declaraciones una y otra vez si utilizas las subrutinas en tus programas.
Mediante el uso de una
subrutina, puedes ejecutar
una o varias sentencias con
una sola instrucción. Para
crear una subrutina, utiliza
la palabra clave Sub, y
luego dale un nombre
específico a la subrutina.
Terminas la subrutina
mediante la palabra clave
EndSub.
Mira la siguiente subrutina
denominada PrintHour, que abre
una ventana de texto y muestra la
hora actual.
7. Subrutinas en programas de Small Basic
En este programa,
utilizamos la instrucción
Divide() para ejecutar (o
«llamar») a la subrutina
Divide desde cualquier
ubicación dentro del
programa.
Vamos a tener una mejor comprensión
de las subrutinas escribiendo otro
programa...
8. Vamos a resumir…
¡Felicidades! Ahora ya sabes cómo:
Crear una bifurcación mediante una instrucción Goto.
Crear una subrutina usando una declaración Sub... EndSub.
9. Muestra lo que sabes
Escribir un programa que abre una ventana de texto y
luego realiza los siguientes pasos:
Pregunta al usuario por el nombre,
temperatura, estado del tiempo y viento
de 10 ciudades.
Usos de bifurcación y subrutinas para
determinar y mostrar el número total de:
Ciudades frías
Ciudades frescas
Ciudades cálidas
Ciudades calientes
Ciudades lluviosas
Ciudades ventosas
Notes de l'éditeur
Code:
j = 1
lineQ:
TextWindow.WriteLine(j)
j = j + 1
If j < 30 Then
Goto lineQ
EndIf
In the first line of this program, you create a variable that is named j, and you set its value to 1.
Then you create a label that is named lineQ: with a colon (:) at the end.
In the next line, you tell the computer to display the value of the j variable on the screen.
Then you increase the value of the j variable by 1.
In the fourth line, you determine whether the value of the j variable is smaller than 10.
--If it is, you tell the computer to repeat the lines of code that follow the lineQ: label. In other words, you tell the computer to display the value of the j variable, increase its value by 1, and then determine whether that value is smaller than 10.
--If the value of the j variable is not smaller than 10, you tell the computer to continue to the next part of the program (or to stop running the program if no more code exists).
Code:
j = 1
lineQ:
TextWindow.WriteLine(j)
j = j + 1
If j < 10 Then
Goto lineQ
EndIf
Warning: If you use Goto statements a lot, your code will be difficult to understand and to correct. Although these statements are useful sometimes, you should try to structure your programs so that you rarely use Goto statements.
Code:
start:
TextWindow.WriteLine("How many members are in your family?")
number = TextWindow.ReadNumber()
remainder = Math.Remainder(number, 2)
If remainder = 0 Then
TextWindow.WriteLine("Your family has an even number of members.")
Else
TextWindow.WriteLine("Your family has an odd number of members.")
EndIf
Goto start
If you use subroutines, your programs will be easier to read and understand than if you use Goto statements.
In this program, you write the Divide subroutine once, but you can run it from anywhere in the program.
When you instruct the computer to run a subroutine, you use a statement that contains the name of the subroutine followed by a set of open and close parentheses. When you use this type of statement, you are calling the subroutine.
Code:
While i < 5
TextWindow.WriteLine("Enter Dividend: ")
Dividend = TextWindow.Read()
TextWindow.WriteLine("Enter Divisor: ")
Divisor = TextWindow.Read()
Divide()
TextWindow.WriteLine("Your answer is: " + Answer)
i = i + 1
EndWhile
Sub Divide
Answer = Dividend / Divisor
EndSub
Solution:
up:
If i < 10 then
TextWindow.WriteLine("")
TextWindow.Write("What is the name of a city? ")
city = TextWindow.Read()
TextWindow.Write("How warm is that city (in degrees Celsius)? ")
temp = TextWindow.Read()
TextWindow.Write("Is it rainy (Y/N)? ")
rainy = TextWindow.Read()
TextWindow.Write("Is it windy (Y/N)? ")
windy = TextWindow.Read()
'Calling subroutines
subtempCount()
subrainyCount()
subwindyCount()
i = i + 1
If i = 10 Then
subOutput()
EndIf
EndIf
Goto up
Sub subtempCount
If temp <= 5 Then
ColdCount = ColdCount + 1
ElseIf temp <= 15 Then
CoolCount = CoolCount + 1
ElseIf temp <= 25 Then
WarmCount = WarmCount + 1
Else
HotCount = HotCount + 1
EndIf
EndSub
Sub subRainyCount
If Rainy = "y" Or Rainy = "Y" Then
RainyCount = RainyCount + 1
EndIf
EndSub