2. Condiciones y bucles
En esta lección, usted aprenderá cómo:
Escribir programas que llevan a cabo
diferentes instrucciones en función de si una
o más condiciones lógicas son verdaderas.
Escribir programas que repiten las
instrucciones hasta que se produce un evento
específico.
3. Condiciones en Programas Small Basic
Veamos el siguiente programa:
¿Te gustaría especificar las condiciones que controlan cómo se ejecuta el
programa?
Este programa indica a la computadora que muestre «Feliz año nuevo»
sólo si hoy es 1ro de enero.
Tenga en cuenta que este programa tiene las palabras claves If (Si), Then
(Entonces) y EndIf (FinSi)
4. Condiciones en Programas Small Basic
Ahora, vamos a escribir un
programa en el que se especifica
una acción alternativa para llevar a
cabo si la condición es falsa.
Al ejecutar el programa, el ordenador muestra uno de
los siguientes resultados:
5. Condiciones en Programas Small Basic
En programación, puedes hacer lo mismo en más de una forma. Como
programador, puedes elegir la mejor manera.
En este ejemplo, habrás notado que la
segunda condición del programa
repite mucha información de la
primera condición.
Vamos a reducir la repetición
mediante la palabra clave Else
(Sino).
Ambos programas dan el mismo resultado, pero puedes utilizar menos palabras
claves If, Then y EndIf si utilizas la palabra clave Else.
6. Miremos otro ejemplo...
Condiciones en Programas Small Basic
Observa el uso de If, Then, Else y
EndIf en el programa.
Estás escribiendo un programa
complejo, y deseas comprobar si
el usuario escribió un número par
o impar.
7. Cuando escribes un programa, puedes especificar tantas condiciones como
quieras mediante la palabra clave ElseIf. También puedes especificar una o varias
operaciones para que la computadora lleve a cabo, en función de que la
condición sea verdadera cuando se ejecuta el programa.
Condiciones en Programas Small Basic
Echemos un vistazo a
esto con un ejemplo.
En este ejemplo, cada
condición contiene una
declaración única que evalúa la
computadora. Cuando el
computador evalúa una
declaración como verdadero,
el equipo realiza la operación
para esa condición y luego
procede al final.
8. Bucles en Programas Small Basic
Así que, vamos a explorar algunas declaraciones de bucle…
Se puede utilizar un bucle para
instruir a la computadora para
ejecutar una o varias sentencias más
de una vez.
Puedes utilizar un bucle For (Para)
si sabes cuántas veces se desea
que el ordenador repita las
instrucciones.
Puedes utilizar un bucle While
(Mientras) si deseas que el programa
repita las instrucciones mientras que
una condición específica sea verdadera.
9. Bucles en Programas Small Basic
Haga clic en el botón de la barra de
herramientas.
En este ejemplo, la variable contiene un valor que aumenta en 1 cada vez
que se ejecuta el bucle.
Empecemos por escribir un programa que contiene un bucle For... EndFor.
En general, utiliza un bucle For...EndFor para ejecutar el código un número
determinado de veces. Para gestionar este tipo de bucle, se crea una variable
que registra cuantas veces se ejecuta el bucle.
10. Bucles en Programas Small Basic
Vamos a usar este concepto para imprimir las tablas de multiplicar por el número 5.
11. Bucles en Programas Small Basic
En el ejemplo anterior, el valor de la variable
contador en un bucle For aumenta en 1 cada
vez que el bucle se ejecuta. Sin embargo,
puedes aumentar el valor de este número si
usas la palabra clave Step.
Por ejemplo, puedes
aumentar el valor por 2 si
escribes el siguiente
código:
12. Si no sabes la cantidad del bucle For antes de escribir un
programa, puedes crear un bucle While en vez de un bucle For.
Bucles en Programas Small Basic
Vamos a escribir el
siguiente programa para
demostrar el bucle While:
Cuando se crea un bucle While, se
especifica una condición que ocurre
cuando se inicia el bucle. Pero la
computadora evalúa la condición cada vez
que se repite el bucle. Cuando la condición
se convierte en falsa, el bucle se detiene.
13. Vamos a resumir…
¡Felicidades! Ahora ya sabes cómo:
Escribir programas que evalúan las condiciones lógicas y realizan
operaciones en base a esos resultados.
Escribir programas que repiten una o más instrucciones o un número
determinado de veces o basado en una condición lógica.
14. Demuestra lo que sabes
Crear un programa para convertir una o más
calificaciones de estudiantes de un porcentaje a un
grado de letra. En primer lugar, pedir al usuario que
especifique cuántos grados se calcularán. Luego
pedir al usuario que especifique el primer
porcentaje y convertirlo a un grado de letra según
los siguientes criterios:
Si el porcentaje es más de 75, conviértalo en
una A.
Si el porcentaje es inferior 75, pero mayor o
igual a 60, conviértalo en una B.
Si el porcentaje es inferior a 60, pero mayor o
igual a 35, conviértalo en una C.
Si el porcentaje es inferior a 35, conviértalo a
una D.
Notes de l'éditeur
In Small Basic, you use the Clock object to determine the current date and time.
You use the If keyword to specify a condition that the computer evaluates to determine whether it should perform a particular operation. You use the Then keyword to specify what operation or operations the computer should perform if the condition is true. If the condition is false, the computer skips the operation or operations and proceeds to the next line of the program. You use the EndIf keyword to indicate that the computer should proceed to the next line of the program regardless of whether the condition was true.
In this example, you use the If keyword specify the condition that today is the first day of the first month of the year (January). You use the Then keyword to specify that, if today is the first day of the first month, the computer should run the WriteLine operation. If today is not the first day of the first month, the computer should skip the operation and proceed to the EndIf line of the program.
Code:
If Clock.Day = 1 And Clock.Month = 1 Then
TextWindow.WriteLine("Happy New Year")
EndIf
Code:
If Clock.Hour < 12 then
TextWindow.WriteLine("Did you have your breakfast?")
EndIf
If Clock.Hour > 12 then
TextWindow.WriteLine("Did you have your lunch?")
EndIf
In this program, you specify a condition and an operation to perform if that condition is true. Then you specify a second condition and a second operation to perform if the second condition is true. However, the first condition is true only if the second condition is false, and the second condition is true only if the first condition is false. Therefore, you don’t need to specify the second condition because the computer can determine which operation to perform based only on the first condition. Instead of giving the computer two conditions to evaluate, you can specify that the computer should perform the first operation if the first condition is true and the computer should perform the second operation if the first condition is false.
The result of both approaches is the same. This example shows that you can do the same thing in different ways in programming. It’s up to you!
Code:
If Clock.Hour < 12 Then
TextWindow.WriteLine("Did you have your breakfast?")
Else
TextWindow.WriteLine("Did you have your lunch?")
EndIf
In this program, you first ask the user for a number. Then you create a variable to store the number, and you use the ReadNumber operation to determine what number the user specified.
Next, you create a variable to store the remainder after you divide the user’s number by 2, and you use the Math.Remainder operation to determine whether the remainder is 0.
Finally, you specify that the number is even if the remainder is 0 and that the number is odd if the remainder is not 0.
Code:
TextWindow.Write("Enter a number: ")
number = TextWindow.ReadNumber()
remainder = Math.Remainder(number, 2)
If remainder = 0 Then
TextWindow.WriteLine("The number is even.")
Else
TextWindow.WriteLine("The number is odd.")
EndIf
Code:
TextWindow.WriteLine("What is the current temperature in degrees Celsius? ")
temp = TextWindow.Read()
If temp <= 5 Then
TextWindow.WriteLine("It’s very cold today.")
ElseIf temp <= 15 Then
TextWindow.WriteLine("It’s cool today.")
ElseIf temp <= 25 Then
TextWindow.WriteLine("It’s warm today.")
Else
TextWindow.WriteLine("It’s quite hot today.")
EndIf
Code:
For a = 1 to 10
TextWindow.WriteLine(a)
EndFor
In this program, you first use the WriteLine operation to display "Multiplication Table" on the screen.
Then you create the variable “number” to store the value of 5.
Then you create a For loop with the variable “a” to ensure the WriteLine operation will run 10 times.
You use the WriteLine operation to display the following elements in this order:
--the value that is stored in the “a” variable--the multiplication sign
--the value that is stored in the “number” variable
--the equals sign
--the products of the values of the “a” and “number” variables
Code:
TextWindow.WriteLine("Multiplication Table")
number = 5
For a = 1 to 10
TextWindow.WriteLine(a + " x " + number + " = " + a * number)
EndFor
You can even decrease the value of the loop variable every time that the code runs if you use the Step keyword but specify a negative number. For example, you can write a program that counts backward from 10 to 1 on the screen if you assign the value of -1 to the Step keyword.
Code:
TextWindow.WriteLine("Multiply odd numbers by 5:")
number = 5
For a = 1 to 10 Step 2
TextWindow.WriteLine(a + " x " + number + " = " + a * number)
EndFor
In this example, you first create the “a” variable and set its value to 10.
Next, you create a While loop with a condition that the value of the “a” variable is smaller than or equal to 100. Because you just set the value of that variable to 10, the condition is true when the loop starts.
You use the WriteLine operation to display the value of the “a” variable every time that the loop runs.
In the next statement, you increase the value of the “a” variable by 10 every time that the loop runs.
The loop stops after it runs 10 times because the value of the “a” variable becomes larger than 100.
Code:
a = 10
While (a <= 100)
TextWindow.WriteLine(a)
a = a +10
EndWhile
Solution:
TextWindow.Write("How many student grades would you like to calculate? ")
number = TextWindow.Read()
n = 1
While n <= number
TextWindow.Write("What is the student’s percentage? ")
percentage = TextWindow.Read()
If percentage >= 75 Then
TextWindow.WriteLine("The student’s grade is A.")
ElseIf percentage < 75 And percentage >= 60 Then
TextWindow.WriteLine("The student’s grade is B.")
ElseIf percentage < 60 And percentage >= 35 Then
TextWindow.WriteLine("The student’s grade is C.")
Else
TextWindow.WriteLine("The student’s grade is D.")
EndIf
n = n + 1
EndWhile